我看到以下 Python 文档说“在类中定义变量”将是类变量:
"程序员注:类定义中定义的变量是类变量;它们被所有实例共享。"
但是当我写这样的示例代码时:
class CustomizedMethods(object):
class_var1 = 'foo'
class_var2 = 'bar'
cm1 = CustomizedMethods()
cm2 = CustomizedMethods()
print cm1.class_var1, cm1.class_var2 #'foo bar'
print cm2.class_var1, cm2.class_var2 #'foo bar'
cm2.class_var1, cm2.class_var2 = 'bar','for'
print cm1.class_var1, cm1.class_var2 #'foo bar' #here not changed as my expectation
print cm2.class_var1, cm2.class_var2 #'bar foo' #here has changed but they seemed to become instance variables.
我很困惑,因为我尝试的与 Python 的官方文档不同。