问题描述
class A(object):
aalist = []
ai = 0
def __init__(self):
self.ablist = list()
def add(self):
self.aalist.append(["a","a"])
self.ablist.append(["b","b"])
self.ai = self.ai + 1
class B(A):
def __init__(self):
A.__init__(self)
self.bblist = list()
def badd(self):
self.bblist.append(['c','c'])
for i in range(1,4):
c = B()
c.add()
c.badd()
print c.aalist,c.ablist,c.bblist,c.ai
运行以下代码,结果提示:
run these codes , the result prompts:
[['a', 'a']] [['b', 'b']] [['c', 'c']] 1
[['a', 'a'], ['a', 'a']] [['b', 'b']] [['c', 'c']] 1
[['a', 'a'], ['a', 'a'], ['a', 'a']] [['b', 'b']] [['c', 'c']] 1
我不知道为什么列表会在循环中更新,而int似乎保持静态
I don't know why list get updated in the loop whereas the int seems to keeps static
推荐答案
您正在对它们执行完全不同的操作.请注意,当您执行self.ai = self.ai + 1
时,会将新个整数分配给self.ai
.使用列表时,可以使用append
对其进行处理.另请注意,由于您正在使用int
(它是不可变的),因此不能在适当的位置更改其值.
You're doing completely different operations with them. Note that you assign a new integer to self.ai
when you do self.ai = self.ai + 1
. When you work with the list, you work on it in place using append
. Also note that since you're working with an int
(which is immutable), you can't change it's value in place.
也有证据表明您在这里探索类变量与实例变量.请注意,在您的示例中,ablist
和bblist
是实例变量,而aalist
是类变量.您可以在方法(self.XXlist
)中以相同的方式访问它们,但是当对self.aalist
进行突变时,您将对类中的版本 进行突变.换句话说,self.aalist is A.aalist
将返回True
.这样,您的课程的所有实例都可以共享同一列表.当一个更新列表时,所有其他实例将立即知道(除非它们绑定具有相同名称的实例级别属性-然后该变量将在属性查找中优先).
There's also evidence that you're exploring class variables vs. instance variables here. Note that in your example, ablist
and bblist
are instance variable whereas aalist
is a class variable. You can access them all the same way within a method (self.XXlist
), but when you mutate self.aalist
, you'll mutate the version on the class. In other words, self.aalist is A.aalist
will return True
. This allows all instances of your class to share the same list. When one updates the list, all the other instances will know immediately (unless they bind an instance level attribute with the same name -- That variable will then take precedence in the attribute lookup).
这篇关于在一个班级中更新的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!