Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.