public
Created

Examples to clarify two ways of setting object properties

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
When to use @property decorators?
you start off a class like this
(A)
class Example(object):
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
(B)
class Example(object):
def __init__(self, birth_year):
self.birth_year = birth_year
@property
def age(self):
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:
"obj.x"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.