Python Class Variables: Definition & Usage
One way to define a class variable is by assigning a value directly to a variable within the class, for example:
class MyClass:
class_variable = 10
To use a class variable, it can be accessed through the class name or an instance object, for example:
print(MyClass.class_variable) # 输出:10
my_object = MyClass()
print(my_object.class_variable) # 输出:10
Class variables are shared among all instances of a class, so whether accessed through the class name or an instance object, the same value will be returned. If a certain instance object modifies the value of a class variable, this modification will affect all other instance objects. For example:
my_object = MyClass()
print(my_object.class_variable) # 输出:10
my_object.class_variable = 20
print(my_object.class_variable) # 输出:20
another_object = MyClass()
print(another_object.class_variable) # 输出:10
In the example above, my_object changed the value of class_variable to 20, but the value of class_variable for another_object remained at 10. This is because my_object.class_variable = 20 actually created an instance variable for my_object, which overrides the value of the class variable. If you want to modify the class variable instead of creating an instance variable, you can do so by using the class name, for example:
MyClass.class_variable = 20
print(my_object.class_variable) # 输出:20
print(another_object.class_variable) # 输出:20