gpt4 book ai didi

python - 为什么这个类变量在不同的实例中是相同的?

转载 作者:行者123 更新时间:2023-11-30 23:37:31 24 4
gpt4 key购买 nike

为什么即使创建了该类的新实例,i 仍然保持不变?

class Test(object):
i = 0
def add(self):
Test.i += 1

运行此代码

t = Test()
print t.i
t.add()
t2 = Test()
print t2.i
print t.i

给予

0
1
1

为什么 t.i 和 t2.i 不都等于 0?难道它们不应该等于 0,因为 t2 = Test() 行会将 i 重置为 0?

最佳答案

i 是类变量,而不是实例变量。它绑定(bind)到类本身(这就是为什么您可以编写 Test.i,即使不存在 Test 实例)。

您必须使 i 成为实例变量:

class Test(object):
def __init__(self):
self.i = 0

def add(self):
self.i += 1

关于python - 为什么这个类变量在不同的实例中是相同的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15466824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com