1

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

0

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.