python 类中静态变量
Static variables are those whose lifetime is the entire run of the application. They exist only in single instance per class and are not initiated.
静态变量是指那些生命周期是应用程序整个运行过程的变量 。 它们仅在每个类的单个实例中存在,并且不会启动。
The variables declared inside the class definition and not inside a method is called a class or static variables.
在类定义内部而不是方法内部声明的变量称为类或静态变量 。
Example:
例:
class TestClass:
static_variable = 2
The variable static_variable is accessed as follows,
变量static_variable的访问方式如下:
TestClass.static_variable
Output
输出量
class TestClass:
#creates a class level variable
static_variable = 2
print(TestClass.static_variable)
TestClass.static_variable = 5
print(TestClass.static_variable)
But the above-created static_variable is distinct from any instance-level static_variable, so we could have the below also.
但是上面创建的static_variable与任何实例级static_variable都不同 ,因此我们也可以拥有以下内容。
test_obj = TestClass()
test_obj.static_variable = 6
print(TestClass.static_variable, test_obj.static_variable)
翻译自: https://www.includehelp.com/python/are-static-class-variables-possible.aspx
python 类中静态变量