Your first case creates a class variable, and the second creates an instance variable.
When you do refer self.foo
, Python first checks for a foo
element in the instance's namespace dictionary, and then checks for a foo
element in the class's namespace dictionary.
In the first case, since you created a class variable named tricks
with a mutable type (a list), and didn't re-assign it specifically on the method, modifications to that list are available to every instance of the class.
In your second case, things are identical except that you hid the class variable with an instance variable of the same name, so from that point on, all references to self.tricks
refer to the instance variable instead of the class variable.
The second case illustrated:
mytest.__dict__ = {
'name': 'test1',
'tricks': [], # this doesn't get updated
}
t1.__dict__ = {
'name': 'some_passed_name'
'tricks': ['some_passed_name'],
}