In the both case, you replacing the self.name
to a new value.
In the first case you're mutating the self.tricks
list, mutating a list don't replace it. so during the whole execution you have a single list, being mutated.
In the second case, the line self.tricks=[name]
is changing the list, creating a new list object.
You can easily introspect this like:
class mytest:
name = "test1"
tricks = list()
print("tricks id during class definition is: {}".format(id(tricks)))
def __init__(self, name):
self.name = name
print("self.tricks id at the beginning of __init__ is: {}".format(id(self.tricks)))
self.tricks = [name]
print("self.tricks id after being replaced is: {}".format(id(self.tricks)))
print("but mytest.tricks id is still: {}".format(id(mytest.tricks)))
self.tricks.append(name)
t1=mytest("hello world")
t2=mytest("bye world")
Giving:
tricks id during class definition is: 140547174832328
self.tricks id at the beginning of __init__ is: 140547174832328
self.tricks id after being replaced is: 140547174831432
but mytest.tricks id is still: 140547174832328
self.tricks id at the beginning of __init__ is: 140547174832328
self.tricks id after being replaced is: 140547174830600
but mytest.tricks id is still: 140547174832328