[英]How do I refer to static class variable in Python?
I have a 'static' class 我有一个“静态”课程
class A:
a = 1
@staticmethod
def doStuff():
foo(A.a)
Now I need a derived class 现在我需要一个派生类
class B(A):
a = 2
that basically does 基本上可以
@staticmethod
def doStuff():
foo(B.a)
If A would not be a pseudo static class, I could just derive B from A and 如果A不是伪静态类,我可以从A派生B,
foo(self.a)
would do what I want. 会做我想要的。 Is there a way to avoid copying doStuff() into class B and replace foo(Aa) with foo(Ba)?
有没有一种方法可以避免将doStuff()复制到类B中,并用foo(Ba)替换foo(Aa)? Something along the line of referring to the class in a 'self' way and having class A s doStuff look like
类似于以“自我”方式引用类并让A类的doStuff看起来像
def doStuff():
foo(class_self.a)
? ?
I assume you mean class
instead of def
in your code. 我假设您的意思是
class
而不是def
。
The answer is not to use a staticmethod, but a classmethod. 答案不是使用静态方法,而是使用类方法。 This would behave exactly as you want.
这将完全按照您想要的方式运行。
class A:
a = 1
@classmethod
def doStuff(cls):
foo(cls.a)
class B(A):
a = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.