为什么这个类变量在不同的实例之间相同? [英] Why is this class variable the same across different instances?

查看:104
本文介绍了为什么这个类变量在不同的实例之间相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在创建类的新实例后仍保持不变?

Why does i remain the same even after a new instance of the class is created?

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


$ b b

赠与

Gives

0
1
1

为什么ti和t2.i都不等于0?应该不是他们等于0,因为行 t2 = Test()会将i重置为0?

Why didn't both t.i and t2.i equal 0? Shouldn't they have equaled 0 because the line t2 = Test() would have reset i to 0?

推荐答案

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

i is a class variable, not an instance variable. It is bound to the class itself (which is why you can write Test.i, even if no instances of Test exist).

您必须使 i 一个实例变量:

You have to make i an instance variable:

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

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

这篇关于为什么这个类变量在不同的实例之间相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆