Python中的静态类变量 [英] Static class variables in Python
问题描述
有可能在python中有静态类变量或方法吗?
Is it possible to have static class variables or methods in python? What syntax is required to do this?
推荐答案
在类定义中声明的变量,而不是方法中的变量是类或静态变量:
Variables declared inside the class definition, but not inside a method are class or static variables:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
As @ millerdev 指出,这创建了一个类级别的i变量,但这与任何实例级别的 i变量,因此您可以有
As @millerdev points out, this creates a class-level "i" variable, but this is distinct from any instance-level "i" variable, so you could have
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
这与C ++和Java不同,但与C#无法使用对实例的引用访问静态成员。
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
@Steve Johnson已经回答了有关静态方法,还记录在Python库参考中的内置函数 a>。
@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@beidy建议 classmethod s over staticmethod,因为该方法接收类类型作为第一个参数,但我仍然有点模糊这种方法的优点超过静态方法。如果你也是,那么它可能没关系。
@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.
这篇关于Python中的静态类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!