You can clone with
When to use @property decorators?
you start off a class like this
def __init__(self, age):
self.age = age
later, you realize I don't really want to store age
I want to store birth_year and calculate age dynamically
so, you can rewrite like this
def __init__(self, birth_year):
self.birth_year = birth_year
return (datetime.now() - self.birth_year).years
if you've got an Example object
ex = Example(...)
whether its implementation is A or B
ex.age still works
in B's case, it works because the @property decorator replaces the attribute access on the instance w/ dynamic computation of the function
in A's case, it works because the attribute is "just there".
(A) age is read/write but computed once upon initialization.
(B) age is read-only and computed upon every attribute lookup.
They both offer the same API though, which is the important thing: