我是 python 的新手,我阅读了有关实例变量的内容:
A variable that is defined inside a method and belongs only to the current instance of a class.
所以我测试一下:
考虑这段代码:
class test:
count=0
def __init__(self):
test.count += 1
我有一个在实例化后添加计数的类。 我运行这个:
t1=test()
t1.count=100
然后我创建新实例:
t2=test()
t2.count # 2
然后创建另一个实例:
t3=test()
t3.count # 3
t2.count # 3
然后:
t1.count # I get 100
我的问题是为什么 t2 和 t3 被更新,但是如果特定实例的实例变量的值发生变化,实例的实例变量没有更新?
请您参考如下方法:
在 t2 和 t3 中,由于您还没有定义实例变量 count,例如 t2。 count 在类作用域中查找名称并评估类变量 test.count。
在t1 中,您创建了一个完全不同 实例变量count,它恰好与类变量同名。 t1.count 因此返回这个实例变量。
