base classes

Skip Montanaro skip at pobox.com
Wed Aug 22 15:22:54 CEST 2001


    pete> One question about classes. I have two classes, both have
    pete> attribute called 'a'

    pete> The question is: cannot 2 base classes have the same attributes?
    pete> What is workaround?

If your intention is that the two should be distinct, try hiding the names
by prepending two underscores to those names:

    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__
{'_a2__a': 2, '_a1__a': 1}

Each instance maintains all its attributes in a single dict, so without some
sort of name mangling you'll get collisions such as you observed.  Python
does work like C++ where you (more-or-less) concatenate base class structs
to build the data structure used by subclass instances.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list