0

I was taking a look at the python tutorial(https://docs.python.org/3/tutorial/classes.html) and found that if you modify a class variable by an object, it will be modified for all the objects. However, I made the following test and found that depending on the type of the variable it might or might not be modified for example if it is a list it gets modified but if it is a string it is not. Do you have any explanation for that. Here is the example:

class Car(object):
    condition = "new"
    add=[]
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
    def modCar(self,mod):
        self.condition=mod
    def addItem(self,item):
        self.add.append(item)

new = Car("DeLorean", "silver", 88)
old = Car("Mercedes","black",30)

old.modCar("old")
print(new.condition)
print(old.condition)

old.addItem("old")
print(new.add)
print(old.add)

And the output:

new
old
['old']
['old']

Thanks

Karroum
  • 1
  • 1
  • `list.append()` is a very **different** kind of modification from assigning to an attribute (rebinding it). – Martijn Pieters Mar 18 '15 at 16:12
  • There is also [Python: Difference between class and instance attributes](http://stackoverflow.com/q/207000) and [Immutable vs mutable types - Python](http://stackoverflow.com/q/8056130) – Martijn Pieters Mar 18 '15 at 16:14

0 Answers0