I wrote this small test case while going through the python tutorial, but I am very confused at the output I received.
class Car(object):
c = "blue"
def __init__(self, model):
self.model = model
c1 = Car("model1")
c2 = Car("model2")
At first I printed the "c" attribute of both instances, and they were both "blue" as expected. Then I wrote:
c1.c = "red"
I then printed out c1.c and c2.c, but only c1.c was changed. c2.c was still "blue". This confused me because according to the documentation the c attributes scope is such that it is accessible by all instances of the class. In the python tutorial, they do an analogousexample where:
class Dog:
tricks = []
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog("fido")
e = Dog("buddy")
d.add_trick("roll")
d.add_trick("play")
print e.tricks
Here, the tricks attribute is modified for both instances. I then modified my code to include a setter method, though I didn't think it should have been necessary:
class Car(object):
f = f1
s = "string"
condition = "new"
c = "blue"
def __init__(self, model, mpg):
self.model = model
#self.c = color
self.mpg = mpg
def change_color(self, x):
self.c = x
I then ran c1.change_color("red") which changed c1.c to "red". However, c2.c is still "blue". I am so confused as to why this is so.