下面的代码让我很困扰:-
class mytest:
name="test1"
tricks=list()
def __init__(self,name):
self.name=name
#self.tricks=[name]
self.tricks.append(name)
t1=mytest("hello world")
t2=mytest("bye world")
print t1.name,t2.name
print t1.tricks,t2.tricks
输出是:-
hello world bye world
['hello world', 'bye world'] ['hello world', 'bye world']
这意味着该列表tricks
由两个实例 t1 和 t2 共享,这已在 9.3.5 节中解释过https://docs.python.org/3/tutorial/classes.html https://docs.python.org/3/tutorial/classes.html
但是,如果我执行以下代码:-
class mytest:
name="test1"
tricks=list()
def __init__(self,name):
self.name=name
self.tricks=[name]
self.tricks.append(name)
t1=mytest("hello world")
t2=mytest("bye world")
x=t1.tricks
if type(x) is list:
print 'a list'
elif type(x) is tuple:
print 'a tuple'
else:
print 'neither a tuple or a list'
print t1.name,t2.name
print t1.tricks,t2.tricks
输出如下:-
a list
hello world bye world
['hello world', 'hello world'] ['bye world', 'bye world']
现在看来名单tricks
不再由这两个实例 t1 和 t2 共享。
我的问题是,这里的机制是什么?