I think I have some misconception about class and instance variables. Here is an example code:
class Animal(object):
energy = 10
skills = []
def work(self):
print 'I do something'
self.energy -= 1
def new_skill(self, skill):
self.skills.append(skill)
if __name__ == '__main__':
a1 = Animal()
a2 = Animal()
a1.work()
print a1.energy # result:9
print a2.energy # result:10
a1.new_skill('bark')
a2.new_skill('sleep')
print a1.skills # result:['bark', 'sleep']
print a2.skills # result:['bark', 'sleep']
I thought that energy
and skill
were class variables, because I declared them out of any method. I modify its values inside the methods in the same way (with self
in his declaration, maybe incorrect?). But the results show me that energy
takes different values for each object (like a instance variable), while skills
seems to be shared (like a class variable). I think I've missed something important...