Suppose you want to write a subclass of some existing class you are
importing from a module you didn't write and that you don't want to
study the internals of, and you want to define a data member i in your
constructor.
As in the following:
from module1 import A
class B(A):
def __init__(self):
A.__init__(self )
self.i= 0
b= B()
Now, 'i' might have already been defined by A or by the call to
A.__init__() so if you define it without knowing that, you could be
changing the behavior of A's methods in unknown ways, which is
obviously a bad thing.
One way to avoid this is to run the following program to clear the name
'i' first:
from module1 import A
a= A()
print a.i
If you get an AttributeError, you know the name 'i' is safe to use. If
you actually get some sort of report from the print statement, then you
will know that 'i' is not safe to use.
This strikes me as a rather odd procedure to go through, but I don't
see any way around it.
It there some other way to handle this issue?
Do I actually need to study the sources for / implementation of
Tkinter.Canvas before I can safely subclass it (and assign attributes
to an instance of the subclass) or clear attribute names as I outlined
above?
Chris Marshall 12 1777
This should prove most enlightening:
import Tkinter
dir(Tkinter.Can vas)
On 10 Nov 2005 14:53:04 -0800, ch************* *****@yahoo.com
<ch************ ******@yahoo.co m> wrote: Suppose you want to write a subclass of some existing class you are importing from a module you didn't write and that you don't want to study the internals of, and you want to define a data member i in your constructor.
As in the following:
from module1 import A
class B(A): def __init__(self): A.__init__(self ) self.i= 0 b= B()
Now, 'i' might have already been defined by A or by the call to A.__init__() so if you define it without knowing that, you could be changing the behavior of A's methods in unknown ways, which is obviously a bad thing.
One way to avoid this is to run the following program to clear the name 'i' first:
from module1 import A a= A() print a.i
If you get an AttributeError, you know the name 'i' is safe to use. If you actually get some sort of report from the print statement, then you will know that 'i' is not safe to use.
This strikes me as a rather odd procedure to go through, but I don't see any way around it.
It there some other way to handle this issue?
Do I actually need to study the sources for / implementation of Tkinter.Canvas before I can safely subclass it (and assign attributes to an instance of the subclass) or clear attribute names as I outlined above?
Chris Marshall
-- http://mail.python.org/mailman/listinfo/python-list
--
Steve Juranich
Tucson, AZ
USA
Steve Juranich wrote: This should prove most enlightening:
import Tkinter dir(Tkinter.Can vas)
Huh?
Chris Marshall
Fredrik Lundh wrote: ch************* *****@yahoo.com wrote:
Now, 'i' might have already been defined by A or by the call to A.__init__() so if you define it without knowing that, you could be changing the behavior of A's methods in unknown ways, which is obviously a bad thing.
http://docs.python.org/tut/node11.ht...00000000000000
</F>
I see. Thanks for the link.
So putting two underscores in front of an instance variable (or any
identifier used inside the scope of a class statement) invokes a name
mangling mechanism ( __x becomes __classname_x internally)
so the following would not result in any conflicts
class A:
def __init__(self):
self.__i= 0
class B(A):
def __init__(self):
A.__init__(self )
self.__i= 1
Is it commonplace to use underscores when defining derived class
instance variables, or is this considered against the grain of python?
Chris Marshall ch************* *****@yahoo.com wrote: Suppose you want to write a subclass of some existing class you are importing from a module you didn't write and that you don't want to study the internals of
No need to study its internals. Fire up a Python interpreter and
inspect its outside: import foomodule dir(foomodule.F ooClass)
Any attributes named there should be avoided in your subclasses if you
don't want to clobber existing behaviour.
--
\ "Those who will not reason, are bigots, those who cannot, are |
`\ fools, and those who dare not, are slaves." -- "Lord" George |
_o__) Gordon Noel Byron |
Ben Finney ch************* *****@yahoo.com wrote:
(snip) So putting two underscores in front of an instance variable (or any identifier used inside the scope of a class statement) invokes a name mangling mechanism
(snip)
Is it commonplace to use underscores
I assume you mean double underscore...
when defining derived class instance variables, or is this considered against the grain of python?
I don't know if it's 'commonplace', but that's something I only do when
I absolutely want to protect a given attribute of a base class from
being accidentally overriden by a derived class. Else I use the usual
convention ('_name' => implementation, 'name' => API), and assume users
of my code will read the documentation (or the source FWIW) before
subclassing. Note that since 'users of my code' are mostly my coworkers
and I, this is a quite sensible assumption !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
I see what you mean now.
It would indeed be enlightening if I wanted to study the internals of
Tkinter, and perhaps one day I will.
Your suggestion ('_name' -> implementation, 'name' -> API) makes sense
as a convention between programmers that know a fair amount about each
other's classes before using them.
I don't think it is reasonable in general to only subclass from base
classes you have studied the full API of, however. The double
underscore is a decent solution to my problem.
I imagine it must be used a lot in domains where people are making
heavy use of third party python code.
Chris Marshall
<ch************ ******@yahoo.co m> wrote:
... I don't think it is reasonable in general to only subclass from base classes you have studied the full API of, however. The double
I think you underestimate the level of coupling that inevitably occurs
between base and derived classes. In general, such coupling being
strong, knowing the full API of the base class is inevitable (although
in some special corner-case, when you do only need to add private data,
you may, exceptionally, get away with less knowledge).
Alex This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Sridhar R |
last post by:
Consider the code below,
class Base(object):
pass
class Derived(object):
def __new__(cls, *args, **kwds):
# some_factory returns an instance of Base
# and I have to derive from this instance!
|
by: Shao Zhang |
last post by:
Hi,
I am not sure if the virtual keyword for the derived classes are
required given
that the base class already declares it virtual.
class A
{
public:
virtual ~A();
|
by: Microsoft |
last post by:
Base class:
class AssetBase
{
string _clli;
public string CLLI
{
get
|
by: Baski |
last post by:
Base class:
class AssetBase
{
string _clli;
public string CLLI
{
get
|
by: John Glover |
last post by:
I'm having a very strange problem with XML serialization. I'm writing web
services which pass instances of various classes back and forth as parameters
and return values of web methods. The problem is that in my derived classes,
the XML that is automatically generated is lacking the properties of the base
class. For example:
public class...
| |
by: Peter Nofelt |
last post by:
Hey All,
I am having issue with serializing a class and its base class using
..net 2.0. I am using IXmlSerializable
I've provided code displaying my at the bottom of this post. Thanks
ahead of time for any help or feedback.
Cheers,
Peter
|
by: Taran |
last post by:
Hi All,
I tried something with the C++ I know and some things just seem
strange.
consider:
#include <iostream>
using namespace std;
|
by: Jeff Mason |
last post by:
Hi,
I'm having a reflection brain fog here, perhaps someone can set me on the right
track.
I'd like to define a custom attribute to be used in a class hierarchy.
What I want to do is to have an attribute which can be applied to a class definition
of a class which inherits from a base, mustinherit class. I want to define methods
in the...
|
by: Goran Djuranovic |
last post by:
Hi all,
Is there a way to retrieve a derived class name inside a subroutine or a
function of the base class? I am trying to get some data from the database,
based on which derived class is calling the subroutine. I know the base
class name can be retrieved by using reflection namespace:...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |