Coming from a C++ background, I'm a little bemused by Python's variable usage and, in particular, the creation of class objects. Consider this code below:
class Cat(object):
"""My pet cat"""
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "{0}, {1}".format(self.name, self.age)
class Age(object):
def __init__(self, a):
self.age = a
def __repr__(self):
return "{0}".format(self.age)
With the output:
>>> name='milo'
>>> age =4
>>> m = Cat(name, age)
>>> print(m)
milo, 4
>>> age +=1
>>> print(m)
milo, 4
>>> name='rex'
>>> age =Age(4)
>>> rex = Cat(name, age)
>>> print(rex)
rex, 4
>>> age.age += 55
>>> print(rex)
rex, 59
For some reason rex
gets older, and milo
stays 4 years old. So if I make another cat to replace the old one:
>>> age.age -=55
>>> spike = Cat('spike', age )
>>> print(spike)
spike, 4
>>> print(rex)
rex, 4
Both spike
and rex
are now the same age.
How should I code the Cat
and Age
classes so that I don't accidentally rejuvenate the old cats?
And why is it that 'Milo' does not age by one year when doing age +=1
?