Home > OS >  Inheritance and function overriding in Python
Inheritance and function overriding in Python

Time:10-07

In python, if class C inherits from two other classes C(A,B), and A and B have methods with identical names but different return values, which value will that method return on C?

CodePudding user response:

"Inherits two methods" isn't quite accurate. What happens is that C has a method resolution order (MRO), which is the list [C, A, B, object]. If you attempt to access a method that C does not define or override, the MRO determines which class will be checked next. If the desired method is defined in A, it shadows a method with the same name in B.

>>> class A:
...   def foo(self):
...     print("In A.foo")
...
>>> class B:
...   def foo(self):
...     print("In B.foo")
...
>>> class C(A, B):
...   pass
...
>>> C.mro()
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
>>> C().foo()
In A.foo

CodePudding user response:

MRO order will be followed now, if you inherit A and B in C, then preference order goes from left to right, so, A will be prefered and method of A will be called instead of B

  • Related