Created
August 10, 2013 19:25
-
-
Save six5532one/6201787 to your computer and use it in GitHub Desktop.
Examples to clarify two ways of setting object properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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