The following code troubles me:-
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
The output is:-
hello world bye world
['hello world', 'bye world'] ['hello world', 'bye world']
meaning that the list tricks
is shared by the two instances t1 and t2, which has been explained in the section 9.3.5 of https://docs.python.org/3/tutorial/classes.html
However, if I execute the following code:-
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
The output is the following:-
a list
hello world bye world
['hello world', 'hello world'] ['bye world', 'bye world']
Now it seems that the list tricks
is no longer shared by those two instances t1 and t2.
My question is, what are the mechanics here?