[英]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, ie, C(A,B) where B is just another class.在类 A 中,我有类变量和类方法,我想在多重继承后在类 C 中访问它们,即 C(A,B) ,其中 B 只是另一个类。 I have found that I can access both class method and variable via self.
我发现我可以通过自我访问类方法和变量。 , super().
,超级()。 or by using the class name it self, ie, A.
或者通过使用它自己的类名,即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
问候, 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())
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 , 1.如果你在类
C
有另一个info()
,不管是类方法还是实例方法,
self.info()
will call that method defined in class C
, NOT the one in class A
将调用
C
类中定义的方法,而不是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 , 2.如果继承顺序对于
class C(B, A)
,并且你在类B
有另一个info()
无论是类方法还是实例方法,
super().info()
will call that method defined in class B
, NOT the one in class A
将调用
B
类中定义的方法,而不是A
类中定义的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.