Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Use Python @propery to fix bad interface (the bad interface)

  • @property

When we created the class the first time we wanted to have a field representing the age of a person. (For simplicity of the example we onlys store the years.)


class Person():
    def __init__(self, age):
        self.age = age

p = Person(19)
print(p.age)       # 19

p.age = p.age + 1
print(p.age)       # 20

Only after releasing it to the public have we noticed the problem. Age changes.

We would have been better off storing birthdate and if necessary calculating the age.

How can we fix this?