base classes
Fredrik Stenberg
mail at fredriks.org
Wed Aug 22 08:48:45 EDT 2001
On Wed, 22 Aug 2001, Pete wrote:
> One question about classes. I have two classes, both have attribute called
> 'a'
> class a1:
> def __init__( self ):
> self.a = 1
> class a2:
> def __init__( self ):
> self.a = 2
> class aa( a1, a2 ):
> def __init__( self ):
> a1.__init__( self )
> a2.__init__( self )
>
> AA = aa()
> print AA.__dict__
> --------------------------------------
> this code prints:
> {'a': 2}
>
> but if I change self.a to self.a_ in class a1:
> class a1:
> def __init__( self ):
> self.a_ = 1
> class a2:
> def __init__( self ):
> self.a = 2
> class aa( a1, a2 ):
> def __init__( self ):
> a1.__init__( self )
> a2.__init__( self )
>
> AA = aa()
> print AA.__dict__
> ------------------------------------------
> I got:
> {'a_': 1, 'a': 2}
>
> The question is: cannot 2 base classes have the same attributes? What is
> workaround?
>
I'm not sure this is what you want but you can always prefix the attr
with "__" to get name mangling...
Check out,
http://www.python.org/doc/current/tut/node11.html#SECTION0011600000000000000000
(section 9.6 in the python tutorial)
Example;
class a1:
def __init__( self ):
self.__a = 1
def printa1(self):
print self.__a
class a2:
def __init__( self ):
self.__a = 2
def printa2(self):
print self.__a
class a3:
def __init__( self ):
self.a = 3
def printa3(self):
print self.a
class aa( a1, a2,a3 ):
def __init__( self ):
a1.__init__( self )
a2.__init__( self )
a3.__init__( self )
AA = aa()
-----------------------------
>>> AA.printa1()
1
>>> AA.printa2()
2
>>> AA.a
3
/fredriks
More information about the Python-list
mailing list