如果子类使用相同的方法名扩展两个类,则子类调用哪个方法

Shr*_*ava 1 python python-2.7

我有2个类--say A和B作为1个class -child类的父级,A和B类都有方法myMethod.现在,如果我在子类中调用mymethod,那么它指的是什么?

jon*_*rpe 5

它调用方法解析顺序(MRO)中首先出现的那个,它取决于定义子类继承的顺序:

>>> class A(object):
    def method(self):
        print('A.method')


>>> class B(object):
    def method(self):
        print('B.method')


>>> class C(A, B):
          # ^ A appears first in definition
    pass

>>> C.mro()
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>]
                     # ^ and therefore is first in the MRO
>>> C().method()
A.method  # so that's what gets called
Run Code Online (Sandbox Code Playgroud)

为了确保调用方法的所有实现,您可以使用super,这将使MRO 的下一个实现"上升":

>>> class A(object):
    def method(self):
        print('A.method')
        super(A, self).method()  # this will be resolved to B.method for C


>>> class B(object):
    def method(self):
        print('B.method')


>>> class C(A, B):
    pass

>>> C.mro()  # same as before
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>]
>>> C().method()
A.method
B.method
Run Code Online (Sandbox Code Playgroud)

请注意,你必须要小心一点这样做,你有多重继承,如添加superB.method会尝试调用object.method,这是不实现的.

  • 在python3中你可以使用`super().method()`,在旧的python中它并不是那么直截了当. (2认同)