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 points out, this creates a class-level i
variable, but this is distinct from any instance-level i
variable, so you could have
(正如@ millerdev指出的那样,这将创建一个类级别的i
变量,但这不同于任何实例级别的i
变量,因此您可以)
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
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.
(这与C ++和Java不同,但与C#并没有太大区别,在C#中,无法使用对实例的引用来访问静态成员。)
See what the Python tutorial has to say on the subject of classes and class objects .
(了解有关类和类对象的Python教程必须说些什么 。)
@Steve Johnson has already answered regarding static methods , also documented under "Built-in Functions" in the Python Library Reference .
(@Steve Johnson已经回答了有关静态方法的问题 ,该方法也记录在Python Library Reference中的“内置函数”下 。)
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@beidy recommends classmethod s 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.
(@beidy建议使用classmethod而不是staticmethod,因为该方法随后将类类型作为第一个参数,但是对于这种方法相对于staticmethod的优点,我仍然有些模糊。)
If you are too, then it probably doesn't matter. (如果您也是,那可能没关系。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…