面试题答案
一键面试- Python确定调用顺序的方式:
- 在Python中,这种情况涉及到方法解析顺序(Method Resolution Order,MRO)。当在
C
类的实例中调用method
方法时,Python会按照C3线性化算法确定的MRO来查找方法。 - 对于
class C(A, B)
,MRO首先查找C
类本身,如果C
类中有method
方法,就调用C
类的method
方法。如果C
类中没有找到,就按照继承顺序,先查找A
类,再查找B
类。
- 在Python中,这种情况涉及到方法解析顺序(Method Resolution Order,MRO)。当在
- 明确调用A类的
method
方法的做法:- 可以使用
super()
函数结合类名来明确调用A
类的method
方法。 - 示例代码如下:
- 可以使用
class A:
def method(self):
print("This is A's method")
class B:
def method(self):
print("This is B's method")
class C(A, B):
def method(self):
print("This is C's method")
super(C, self).method() # 调用A类的method方法
c = C()
c.method()
在上述代码中,C
类重写了method
方法,在C
类的method
方法中,使用super(C, self).method()
明确调用了A
类的method
方法。当调用c.method()
时,首先打印This is C's method
,然后打印This is A's method
。因为C
继承自A
和B
,按照MRO,super(C, self).method()
会找到A
类的method
方法。