Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

python - Python中可以使用静态类变量吗?(Are static class variables possible in Python?)

Is it possible to have static class variables or methods in Python?

(Python中是否可以有静态类变量或方法?)

What syntax is required to do this?

(为此需要什么语法?)

  ask by Andrew Walker translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(如果您也是,那可能没关系。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...