如何在Python中声明静态属性?
这里写了我如何声明一个方法:
Static methods in Python?
最佳答案
在Python的类级别定义的所有变量均被视为静态
class Example:
Variable = 2 # static variable
print Example.Variable # prints 2 (static variable)
# Access through an instance
instance = Example()
print instance.Variable # still 2 (ordinary variable)
# Change within an instance
instance.Variable = 3 #(ordinary variable)
print instance.Variable # 3 (ordinary variable)
print Example.Variable # 2 (static variable)
# Change through Class
Example.Variable = 5 #(static variable)
print instance.Variable # 3 (ordinary variable)
print Example.Variable # 5 (static variable)
在类中,您可以使用相同的名称拥有两个不同的变量(一个静态变量和一个普通变量)。
不要困惑。
关于python - 如何在Python中声明静态属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27481116/