当继承多个类python时,哪个类返回日志记录方法



假设我们有3个类,2个父类和1个从双亲继承的子类:

import logging
class A:
    def __init__(self):
        self.parent_logger = logging.getLogger("parent")
        
class B:
    def __init__(self):
        self.parent_logger = logging.getLogger("parent")
        
class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)
        
test_class = C()
test_class.parent_logger.info("sample")

当实例化类C并在其上调用父记录器时,parent_logger是从哪个类使用的?

顺序是从左到右的,所以在这种情况下,记录器是从类A中使用的,因为您声明C继承自(A, B)。首先搜索A的记录器,然后搜索它的所有父类(如果有(,然后搜索B。如果您将C定义为class C(B, A):,则首先搜索B,然后使用B中的记录器。

https://www.educative.io/answers/what-is-mro-in-python

最新更新