先放代码:(python2.7.10)
class Res(object):
x = []
def __init__(self, t):
for i in t:
self.x.append(i)
A = Res(['a', 1])
B = Res(['b', 2])
print A.x
print B.x
输出结果是:
['a', 1, 'b', 2]
['a', 1, 'b', 2]
按理说不应该各是各的吗?
改成下面这种形式就好了
def __init__(self, t):
self.x = t
输出:
['a', 1]
['b', 2]
请问这个问题是 list.append() 导致的吗?
This is where you should read the basic tutorials
x here is not an instance variable, but a class variable. The difference between class variables and instance variables is that the former is common to all objects, while the latter belongs to each instance.
self.x.append(i) dereferences member variables first when dereferencing x, but you have not initialized the member variable named x before, so the last dereference is the class variable
As @zwillon said, when self.x in your code cannot find instance attributes, the higher-level class attributes will be used. Writing instance properties like above is the correct approach.