如何在 Python 中创建类(即 静态)变量或方法?
原文由 Andrew Walker 发布,翻译遵循 CC BY-SA 4.0 许可协议
@Blair Conrad 说在类定义内而不是在方法内声明的静态变量是类或“静态”变量:
>>> class Test(object):
... i = 3
...
>>> Test.i
3
这里有一些问题。承接上面的例子:
>>> t = Test()
>>> t.i # "static" variable accessed via instance
3
>>> t.i = 5 # but if we assign to the instance ...
>>> Test.i # we have not changed the "static" variable
3
>>> t.i # we have overwritten Test.i on t by creating a new attribute t.i
5
>>> Test.i = 6 # to change the "static" variable we do it by assigning to the class
>>> t.i
5
>>> Test.i
6
>>> u = Test()
>>> u.i
6 # changes to t do not affect new instances of Test
# Namespaces are one honking great idea -- let's do more of those!
>>> Test.__dict__
{'i': 6, ...}
>>> t.__dict__
{'i': 5}
>>> u.__dict__
{}
注意实例变量 t.i
当属性 i
直接设置在 t
时,实例变量如何与“静态”类变量不同步这是因为 i
被重新绑定到 t
命名空间中,它不同于 Test
命名空间。如果要更改“静态”变量的值,则必须在最初定义它的范围(或对象)内更改它。我将“static”放在引号中是因为 Python 并没有真正意义上的 C++ 和 Java 那样的静态变量。
虽然它没有说任何关于静态变量或方法的具体信息,但 Python 教程 有一些关于 类和类对象 的相关信息。
@Steve Johnson 还回答了有关静态方法的问题,也记录在 Python 库参考中的“内置函数”下。
class Test(object):
@staticmethod
def f(arg1, arg2, ...):
...
@beid也提到了classmethod,它类似于staticmethod。类方法的第一个参数是类对象。例子:
class Test(object):
i = 3 # class (or static) variable
@classmethod
def g(cls, arg):
# here we can use 'cls' instead of the class name (Test)
if arg > cls.i:
cls.i = arg # would be the same as Test.i = arg1
原文由 millerdev 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
2 回答834 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
在类定义内声明但不在方法内声明的变量是类或静态变量:
正如 @millerdev 指出的那样,这会创建一个类级别
i
变量,但这与任何实例级别i
变量不同,因此您可以拥有这与 C++ 和 Java 不同,但与 C# 没有太大区别,在 C# 中无法使用对实例的引用来访问静态成员。
看看 Python 教程关于类和类对象的主题是怎么说的。
@Steve Johnson 已经回答了有关 static methods 的问题,也在 Python Library Reference 的“内置函数”下进行了 记录。
@beidy 推荐 classmethod 优于 staticmethod,因为该方法随后接收类类型作为第一个参数。