如何在 Python 中创建静态类变量或方法?
最佳答案
在类定义中声明但不在方法中的变量是类或静态变量:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
作为@ millerdev指出,这会创建一个类级 i
变量,但这与任何实例级 i
变量不同,因此您可以拥有
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
这与 C++ 和 Java 不同,但与 C# 没有太大不同,后者不能使用对实例的引用来访问静态成员。
见 what the Python tutorial has to say on the subject of classes and class objects .
@Steve Johnson 已经回答了 static methods ,也记录在 "Built-in Functions" in the Python Library Reference 下.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@beidy 推荐 classmethod s over staticmethod,因为该方法随后接收类类型作为第一个参数。
关于python - Python中的静态类变量和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68645/