SuperDisk
SuperDisk

Reputation: 2840

Python Multiple Inheritance - Call a method of a class, but which one?

class MyClass(Class1, Class2):
    pass

Both parents have a getImage method.

thing = MyClass()
thing.getImage() #I want to call Class1's
thing.getImage() #I want to call Class2's

Which getImage gets called? How do I specify which one to call?

Upvotes: 0

Views: 78

Answers (1)

mgilson
mgilson

Reputation: 309899

In this case, thing.getImage will call Class1.getImage provided that it exists. If you want to call the other, you can use the longer form:

Class2.getImage(thing)

These things can be inspected via the class's method resolution order (__mro__):

>>> class foo(object): pass
... 
>>> class bar(object): pass
... 
>>> class baz(foo,bar): pass
... 
>>> print baz.__mro__
(<class '__main__.baz'>, <class '__main__.foo'>, <class '__main__.bar'>, <type 'object'>)

This shows that baz is searched for the method first, then foo, then bar and finally object.

Further reading about multiple inheritance

Further reading about mro

Upvotes: 2

Related Questions