Python Forum

Full Version: problem with simple class code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm havingg a problem with my code, I dont know why my code doesn't work. It works well when I use a string value to the condition variable, but not when I try to change a list.
Here is a copy of an example that works:
class Car(object):
    condition = "new"
    def __init__(self, color):
        self.color = color
    def drive(self):
        self.condition = "used"

chevy = Car("Blue")
print (chevy.condition) 
ford = Car("Red")
print (ford.condition)
chevy.drive()
print (chevy.condition)
print (ford.condition)
Result:
Output:
new new used new
The ford condition is new as it shouldbe considerning the ford.drive() wasn't executed.
Now when i change the condition value for a list it doesnt work:
class Car(object):
    condition = ["0","0"]
    def __init__(self, color):
        self.color = color
    def drive(self):
        self.condition[0] = "1"

chevy = Car("Blue")
print (chevy.condition)
ford = Car("Red")
print (ford.condition)
chevy.drive()
print (chevy.condition)
print (ford.condition)
Output:
['0', '0'] ['0', '0'] ['1', '0'] ['1', '0']
In this example the ford condition change despite the ford.drive()has not been executed.
Does anyone know why this happens?
Please post your code in Python code tags. You can find help here.
Attribute condition is defined before the initialization, so it's an attribute of the class itself and not of the class objects. When you modify the value of that attribute it therefore modifies it for all objects.
class Car(object):
    condition = ["0","0"]
    def __init__(self, color):
        self.color = color
    def drive(self):
        clone = self.condition[:]
        clone[0] = '1'
        self.condition = clone
try clone/make a copy of self.condition, make changes on that clone and ressign instead of mutating it.
There is a easier solution than starting clone/copy stuff @ka06059.
class Car:
    def __init__(self, color):
        self.color = color
        self.condition = ["0","0"]

    def drive(self):
        self.condition[0] = "1"
Test.
>>> chevy = Car("Blue")
>>> ford = Car("Red")
>>> 
>>> # So now setting condition will only affect one object
>>> chevy.drive()
>>> chevy.condition
['1', '0']
>>> ford.condition
['0', '0']
>>> 
Orgianl post with class attribute:
Class attribute are owned by the class itself,so the attribute has the same value for each instance(object) of a particular class.

What i show are instance attribute:
Instance attributes are owned by the specific instance(object) of the class,so can vary from instance to instance of a specific class.
nice,thanks for the alt solution!