dataviews
dataviews

Reputation: 3140

which class returns the logging method when inheriting multiple classes python

Suppose we have 3 classes, 2 parent and 1 child that inherits from both parents:

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")

Which class does the parent_logger get used from when instantiating class C and calling parent logger on it?

Upvotes: 0

Views: 33

Answers (1)

Filip Müller
Filip Müller

Reputation: 1180

The order is left to right, so in this case the logger gets used from class A, because you declared C as inheriting from (A, B). First A is searched for the logger, then all its parent classes (if it has any) and then B. If you defined C as class C(B, A): then B would be searched first and the logger from B would be used.

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

Upvotes: 1

Related Questions