I need help in writing code that does what I think it should do.
Here's the code:
class Food:
kind = 'fruit'
def __init__(self, name):
self.name = name
a = Food('tomato')
b = Food('cabbage')
print 'a ->', a.kind
print 'b ->', b.kind
print 'change a\'s kind'
a.kind = 'veg'
print 'a ->', a.kind
print 'b ->',b.kind
print 'change kind in the class'
Food.kind = 'meat'
print 'a ->', a.kind
print 'b ->', b.kind
The output I got was this:
a -> fruit
b -> fruit
change a's kind
a -> veg
b -> fruit
change kind in the class
a -> veg
b -> meat
It's the last result that puzzles me. If I've declared 'kind' correctly as a class attribute then surely when I change it in the class with 'Food.kind = ' it should change it for both instance. Actually I expected it to change when I gave it the new value via one of the instances also, but it only changed it in one. What am I missing here?
a.kind = 'veg', thekindattribute doesn't exist on the instance, and is references the class variable. If you want it to repoint back at the class variable, thendel a.kindand you will getmeatfor both again.