473,322 Members | 1,493 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

derived / base class name conflicts

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

Nov 10 '05 #1
12 1757
This should prove most enlightening:

import Tkinter
dir(Tkinter.Canvas)

On 10 Nov 2005 14:53:04 -0800, ch******************@yahoo.com
<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, 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
Nov 10 '05 #2
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>

Nov 10 '05 #3
Steve Juranich wrote:
This should prove most enlightening:

import Tkinter
dir(Tkinter.Canvas)


Huh?

Chris Marshall

Nov 11 '05 #4

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

Nov 11 '05 #5
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.FooClass)


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
Nov 11 '05 #6
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('@')])"
Nov 11 '05 #7
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.

Nov 11 '05 #8
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

Nov 11 '05 #9
<ch******************@yahoo.com> 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
Nov 11 '05 #10
ch******************@yahoo.com a écrit :
Your suggestion ('_name' -> implementation, 'name' -> API)
This is not "my" convention, it's *the* (mostly agreed upon) Python
convention. Like 'self', or CONSTANT, or a whole lot of things in Python.
makes sense
as a convention between programmers that know a fair amount about each
other's classes before using them.
No need to know much. dir(modulename.ClassName) is enough.
I don't think it is reasonable in general to only subclass from base
classes you have studied the full API of, however.
Depends on your definition of "studying the full API" !-)

Now if your fear is to accidentally override something in the base
class, it's just a matter of:
print "API:"
print [name for name in dir(modulename.ClassName) \
if not name.startswith('_')]

print "IMPLEMENTATION:"
print [name for name in dir(modulename.ClassName) \
if not name.startswith('_')]
The double
underscore is a decent solution to my problem.
Possibly. It can also become a PITA. But it's you who know what your
code need !-)
I imagine it must be used a lot in domains where people are making
heavy use of third party python code.


I almost never used it (perhaps half-a-dozen times, and only in
frameworks abstract base classes), and rarely saw it in 3rd part source
code.
Nov 22 '05 #11
ch******************@yahoo.com wrote:
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


Be careful here. The above won't result in any conflicts, but related
cases, where you have two classes with the same name in different
modules, may still result in conflicts. See my previous posts on this:

http://groups.google.com/group/comp....3984abaee1c2b5
http://groups.google.com/group/comp....3183a2c01c8ecf

However, I tend not to use double-underscore name mangling, and I don't
think I've ever had a shadowing problem, so clearly I wouldn't have
shadowing problems with double-underscore name mangling either...

STeVe
Nov 22 '05 #12
ch******************@yahoo.com wrote:
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


Be careful here. The above won't result in any conflicts, but related
cases, where you have two classes with the same name in different
modules, may still result in conflicts. See my previous posts on this:

http://groups.google.com/group/comp....3984abaee1c2b5
http://groups.google.com/group/comp....3183a2c01c8ecf

However, I tend not to use double-underscore name mangling, and I don't
think I've ever had a shadowing problem, so clearly I wouldn't have
shadowing problems with double-underscore name mangling either...

STeVe
Nov 22 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
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...
24
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();
6
by: Microsoft | last post by:
Base class: class AssetBase { string _clli; public string CLLI { get
7
by: Baski | last post by:
Base class: class AssetBase { string _clli; public string CLLI { get
6
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...
1
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...
6
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;
15
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...
3
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.