Seeing the following code:
class Super:
powers = 'no power'
def __init__(self, name):
self.name = name
def add_power(self, power):
self.powers = power
dog = Super('dog')
cat = Super('cat')
dog.add_power("bark")
print (dog.powers) # print bark
print (cat.powers) # print no power
it looks like python's class variable is independent to each instance because change dog instance's powers variable from no power to bark does not affect the cat instance's powers variable
However, by doing this:
class Super:
powers = ["no power"]
def __init__(self, name):
self.name = name
def add_power(self, power):
self.powers.append(power)
dog = Super('dog')
cat = Super('cat')
dog.add_power("bark")
print (dog.powers) # print ['no power', 'bark']
print (cat.powers) # print ['no power', 'bark'] # why cat.powers is also affected???
The example shows powers variable (it is a list this time) is static since append an element to dog instance's powers also affects cat instance's powers.
I also experimented with changing the powers to an int and increment powers by 1 by calling add_power, and they don't affect each other. So I am really confused why appending an element to a list which is a class variable affects other instances.
dogdoesn't make it not a class list.