【问题标题】:Python Multiple Inheritance - Call a method of a class, but which one?Python 多重继承 - 调用一个类的方法,但是是哪一个?
【发布时间】:2013-01-17 01:34:43
【问题描述】:
class MyClass(Class1, Class2):
    pass

父母双方都有一个getImage 方法。

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

哪个getImage 被调用?如何指定调用哪一个?

【问题讨论】:

标签: python object multiple-inheritance


【解决方案1】:

在这种情况下,thing.getImage 将调用 Class1.getImage,前提是它存在。如果你想打电话给对方,你可以使用更长的形式:

Class2.getImage(thing)

这些东西可以通过类的方法解析顺序(__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'>)

这表明首先搜索方法baz,然后是foo,然后是bar,最后是object

Further reading about multiple inheritance

Further reading about mro

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多