Search code examples
pythoninstance-methods

How to access class method and class variable from a class to another class's instance method in Python?


Imagine I have three classes as shown in the code snippet.

In class A, I have class variable and class method that I would like to access in class C after multiple inheritance, i.e., C(A,B) where B is just another class. I have found that I can access both class method and variable via self., super(). or by using the class name it self, i.e., A.

The question is, what could be the advised way to access, if any. Or, all three are equally fine? Thanks in advance. Regards, DS

class A():
    school='XYZ'
    def __init__(self):
        print('in init A')
    def feature1(self):
        print('Feature1-A working')
    def feature2(self):
        print('Feature2-A working')

    @classmethod
    def show_avg(cls,m1,m2,m3):
        return (m1+m2+m3)/3
    @classmethod
    def info(cls):
        return cls.school

class B():
    def __init__(self):
        print('in init B')
    def feature3(self):
        print('Feature1-B working')
    def feature4(self):
        print('Feature2-B working')

class C(A,B):
    def __init__(self):
        super().__init__()
        print('in init C') 
    def get_avg_from_super_class(self):
        avg1=self.show_avg(2,3,4)
        avg2=super().show_avg(2,3,4)
        avg3=A.show_avg(2,3,4)
        print('avg by calling self:{}, avg by calling super():{}, avg by alling class name:{}'.format(avg1,avg2,avg3))
    def get_info(self):
        print (A.info())
        print(self.info())
        print(super().info())

Solution

  • For your code, either of the three way works fine.
    But in general, I would say using the class name to access class methods and class variables is the safest way to ensure you are accessing the right methods/variables.

    For example,

    1.If you have another info() in class C whether it's a class method or an instance method,

    self.info()
    

    will call that method defined in class C, NOT the one in class A

    2.If the order of inheritance is different as to class C(B, A), and you have another info() in class B whether it's a class method or an instance method,

    super().info()
    

    will call that method defined in class B, NOT the one in class A