multiple inheritance
Sébastien Boisgérault
Sebastien.Boisgerault at gmail.com
Wed Feb 15 17:41:07 EST 2006
Thomas Girod a écrit :
> Hi.
>
> I think I'm missing something about multiple inheritance in python.
>
> I've got this code.
>
> class Foo:
> def __init__(self):
> self.x = "defined by foo"
> self.foo = None
>
> class Bar:
> def __init__(self):
> self.x = "defined by bar"
> self.bar = None
>
> class Foobar(Foo,Bar):
> pass
>
> fb = Foobar()
> print fb.x
> print fb.__dict__
>
> which returns :
>
> >>>
> defined by foo
> {'x': 'defined by foo', 'foo': None}
>
> So I guess not defining __init__ in my class Foobar will call __init__
> from my superclass Foo. Also __dict__ doesn't show an attribute
> 'bar':None so I guess Bar.__init__ is not called at all.
>
> I would like to have a subclass with all attributes from superclasses
> defined, and only the attribute from the first when there is conflict
> (i.e. in this case, Foobar would be like this but with bar:None)
>
> I tried this :
>
> class Foobar(Foo,Bar):
> def __init__(self):
> Foo.__init__(self)
> Bar.__init__(self)
>
> >>>
> defined by bar
> {'x': 'defined by bar', 'foo': None, 'bar': None}
>
> Here I have all I want, except the value of 'x' comes from the 'Bar'
> superclass rather than Foo. So, to have what I want, I would have to
> invert the two calls to __init__ in order to have the right x value.
>
> What I find awkward here is that the order of __init__ calls matters,
> rather than the order of the classes in the class declaration.
>
> Do you have any ideas of a way to get this multiple inheritance thing
> solved without having to do those __init__ calls ?
try:
class Foo(object):
def __init__(self):
super(Foo, self).__init__() # not really necessary here
self.x = "defined by foo"
class Bar(object):
def __init__(self):
super(Bar, self).__init__()
self.x = "defined by bar"
class FooBar(Foo, Bar):
def __init__(self):
super(FooBar, self).__init__()
and search for the "cooperative methods and super" section
in http://www.python.org/2.2/descrintro.html
Cheers,
SB
>
> Thomas
More information about the Python-list
mailing list