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 (first attempt)

This might have been a good solution, but now we cannot use this as a "fix" as this would change the public interface from p.age to p.age()

from datetime import datetime
class Person():
    def __init__(self, years):
        self.set_birthyear(years)

    def get_birthyear(self):
        return datetime.now().year - self._birthyear

    def set_birthyear(self, years):
        self._birthyear = datetime.now().year - years

    def age(self, years=None):
        if (years):
            self.set_birthyear(years)
        else:
            return self.get_birthyear()



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

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