Skip to main content
 首页 » 编程设计

python之如果它扩展了具有相同方法名称的两个类,哪个方法调用子类

2025年05月04日34www_RR

我有 2 个类 - 比如说 A 和 B 作为 1 个类的父类 - 子类并且 A 类和 B 类都有一个方法 myMethod。 现在,如果我在子类中调用 mymethod,它指的是哪一个?

请您参考如下方法:

它调用方法解析顺序 (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,它将获取下一个实现“up”维修保养:

>>> 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,未实现。