Skip to content

Instantly share code, notes, and snippets.

@six5532one
Created August 10, 2013 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save six5532one/6201787 to your computer and use it in GitHub Desktop.
Save six5532one/6201787 to your computer and use it in GitHub Desktop.
Examples to clarify two ways of setting object properties
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment