我有2个类--say A和B作为1个class -child类的父级,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
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)
请注意,你必须要小心一点这样做,你有多重继承,如添加super到B.method会尝试调用object.method,这是不实现的.
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |