Python中可以使用静态类变量吗? [英] Are static class variables possible in Python?

查看:121
本文介绍了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 

正如@ 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#并没有太大区别,在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.

请参阅关于类和主题的Python教程必须说些什么.类对象.

@Steve Johnson已经回答了有关静态方法,也记录在《 Python库参考》中的内置函数"下.

@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 作为方法,然后接收到类类型作为第一个参数,但是我对这种方法相对于静态方法的优势还是有点模糊.如果您也是,那可能没关系.

@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆