0

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.

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59
  • 1
    This will only occur if the attribute is a **mutable** type. `c` is a `str` which is immutable, but `tricks` is a `list` which is mutable. – Cory Kramer Jun 03 '15 at 14:14
  • so if the attribute is immutable then it is not a truly static variable? – Jeremy Fisher Jun 03 '15 at 14:14
  • 1
    `Car.c = "red"` would be the correct way to change the value of the *class* attribute; `c1.c = "red"` creates a new instance attribute. – chepner Jun 03 '15 at 14:22

0 Answers0