Reputation: 59
I am learning python, For sure a stupid question but I cannot find any answer.
I have an object
class ant(object):
def __init__(self, age):
self.age = 0
def update_age(self)
self.age += 1
pebbles = myant(25)
#check age
print pebbles.age
Now what I want to do is that every time someone checks pebble.age, pebbles automatically runs update_age() internally. Is it possible to do it? or every time I have to check pebbles_age I have to write:
pebbles.update_age()
print pebbles.age.
Thanks a lot
Upvotes: 1
Views: 43
Reputation: 122007
You could implement this using a property:
class Ant(object): # note leading uppercase, per style guide (PEP-8)
def __init__(self): # you ignore the age parameter anyway
self._age = 0
def update_age(self):
self._age += 1
@property
def age(self):
self.update_age()
return self._age
This makes age
read-only, and increments correctly:
>>> an_ant = Ant()
>>> an_ant.age
1
>>> an_ant.age
2
>>> an_ant.age = 10
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
an_ant.age = 10
AttributeError: can't set attribute
Upvotes: 4