0
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?

4

1 回答 1

2

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

于 2013-01-17T01:38:10.013 回答