Skip to content
Search

Python:MethodResolutionOrder

lastmod 2025-04-29created 2024-04-152 edits

The method resolution order is the order in which base classes are searched for a member during lookup.

For details of the algorithm used by the Python interpreter since the 2.3 release, see The Python 2.3 Method Resolution Order.

How to check

The MRO can be checked through a class attribute called __mro__. As a side note, this attribute is a tuple.

print(Son.__mro__)

The output is:

(<class '__main__.Son'>, <class '__main__.Mother'>, 
<class '__main__.Father'>, <class '__main__.Human'>, 
<class 'object'>)

The earlier a value appears in the output, the higher its priority.

In the example above, you can see that priority goes in the order Son -> Mother -> Father -> Human -> and finally the top-level parent, the object class.

Initialization order with multiple inheritance

Here is how to call the __init__ methods of both parent classes with multiple inheritance in Python.

There are two main ways to call the __init__ methods of all parent classes with multiple inheritance:

  1. Calling each parent class's __init__ method directly
  2. Using the super() function (relying on the method resolution order (MRO))

Below is a simple example:

class A:
    def __init__(self, a_param):
        print("A 초기화")
        self.a_param = a_param

class B:
    def __init__(self, b_param):
        print("B 초기화")
        self.b_param = b_param

# 방법 1: 직접 호출 방식
class C(A, B):
    def __init__(self, a_param, b_param, c_param):
        A.__init__(self, a_param)  # A의 __init__ 호출
        B.__init__(self, b_param)  # B의 __init__ 호출
        self.c_param = c_param

# 방법 2: super() 함수 사용
class D(A, B):
    def __init__(self, a_param, b_param, d_param):
        super().__init__(a_param)  # MRO에 따라 A의 __init__ 호출
        B.__init__(self, b_param)  # B의 __init__은 수동으로 호출
        self.d_param = d_param

When using the super() function, note that it follows Python's method resolution order (MRO). In the example above, the MRO of class D is D -> A -> B -> object, so super().__init__() calls A.__init__().

To call __init__ of all parent classes with multiple inheritance, the following pattern is the most common:

class Child(A, B):
    def __init__(self, a_param, b_param, child_param):
        A.__init__(self, a_param)  # A의 초기화
        B.__init__(self, b_param)  # B의 초기화
        self.child_param = child_param  # 자식 클래스의 추가 초기화

This approach is explicit, and the code clearly shows which parent class's initialization method is called.

See also

Favorite site

author Zer0 sitemap