先放代码:(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() 导致的吗?
黄舟2017-04-17 17:54:36
This is where you should read the basic tutorials
class Res(object):
x = []
def __init__(self, t):
for i in t:
self.x.append(i)
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
class Res(object):
x = [1, 2]
def __init__(self, t):
# 直接使用,解引用为成员变量,去掉self.x=3,解引用为类变量
self.x = 3
print self.x
大家讲道理2017-04-17 17:54:36
class Res(object):
def __init__(self,t):
self.x=[]
for i in t:
self.x.append(i)
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.