以下代码困扰我: -
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
Run Code Online (Sandbox Code Playgroud)
输出是: -
hello world bye world
['hello world', 'bye world'] ['hello world', 'bye world']
Run Code Online (Sandbox Code Playgroud)
这意味着列表tricks由两个实例t1和t2共享,这已在https://docs.python.org/3/tutorial/classes.html的 9.3.5节中解释过.
但是,如果我执行以下代码: -
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 …Run Code Online (Sandbox Code Playgroud)