Without property decorator
class Person:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
def get_age(self):
birth_date = datetime.strptime(self.birthday, "%Y-%m-%d").date()
today = datetime.today().date()
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
return age
alice = Person("alice", "1990-03-15")
name = alice.name
birthday = alice.birthday
age = alice.get_age()
Notice that the age looks like a class variable, but it needs to get accessed via a getter function. This is okay, but not very pretty.
With property decorator
Nicer would be:
class Person:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
@property
def age(self):
birth_date = datetime.strptime(self.birthday, "%Y-%m-%d").date()
today = datetime.today().date()
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
return age
alice = Person("alice", "1990-03-15")
name = alice.name
birthday = alice.birthday
age = alice.age
{python}age = alice.age
is much cleaner.