Python 中是否可以有静态类变量或方法?执行此操作需要什么语法?
解决方案在类定义内声明但不在方法内的变量是类或静态变量:
>>>类我的类:...我 = 3...>>>我的课堂3正如@millerdev 指出的那样,这创建了一个类-级别 i 变量,但这与任何实例级别的 i 变量不同,因此您可以拥有
>>>m = MyClass()>>>米 = 4>>>MyClass.i, m.i>>>(3, 4)这与 C++ 和 Java 不同,但与 C# 没有太大不同,其中不能使用对实例的引用来访问静态成员.
请参阅 Python 教程对类和类对象.
@Steve Johnson 已经回答了关于静态方法,也记录在 Python 库参考中的内置函数"下.
C 类:@静态方法def f(arg1, arg2, ...): ...@beidy 推荐 classmethods 而不是 staticmethod,作为方法然后接收类类型作为第一个参数,但我对这种方法相对于静态方法的优势仍然有些模糊.如果你也是,那可能没关系.
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 3As @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)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.
See what the Python tutorial has to say on the subject of classes and class objects.
@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 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 中是否可以使用静态类变量?
发布评论