The docs give the following example:
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
d1 = Dog('Fiddo')
d2 = Dog('Buddy')
d1.add_trick("role over")
d2.add_trick("play dead")
print(d2.tricks)
["role over", "play dead"]
This demonstrate a bad usage of class variables, since we obviously don't want the same list of tricks for all our dogs.
But when I try this:
class A:
static_attr = 'Static'
def __init__(self):
self.object_attr = 'Objective'
def change_static(self, val):
self.static_attr = val
a1, a2 = A(), A()
a1.change_static("Something")
print(a2.static_attr)
I get:
Static
Why could be the reason that for a list object, when modifying the class variable through an object it is modified for all instances, but with a string it doesnt?