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

时间:2015-06-24 11:26:19

标签: python python-2.7

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

2 个答案:

答案 0 :(得分: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

为了确保调用方法的所有实现,您可以使用super,这将获得下一个实现&#34; up&#34; 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

请注意,在有多重继承的情况下,您必须要小心谨慎,因为向super添加B.method会尝试调用object.method isn&# 39; t 已实施。

答案 1 :(得分:0)

它将调用A.我相信它使用层次结构中的第一个,但我并不完全熟悉Python的模型。我刚用这个小样本测试过它:

class A():
    def myMethod(self):
        print("This is A!")

class B():
    def myMethod(self):
        print("This is B!")

class child(A,B):
    def test(self):
        self.myMethod()

test = child()
test.test()
相关问题