Created
May 21, 2014 13:58
-
-
Save dmiro/5dd86caa36b38120eadf to your computer and use it in GitHub Desktop.
Python property class
This file contains hidden or 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
| """ | |
| CHEAT 3: a class with person property using property class | |
| There are two ways to specify a property: | |
| (1) property class | |
| (2) @property decorator | |
| https://docs.python.org/2/library/functions.html#property | |
| """ | |
| class Person(object): # Python > 2.6 you need class clause Person(object) | |
| def __init__(self): | |
| self._name = "" | |
| def get_name(self): | |
| return self._name | |
| def set_name(self, value): | |
| self._name = value | |
| def del_name(self): | |
| del(self._name) | |
| name = property(get_name, set_name, del_name, "property name") | |
| # Test | |
| person = Person() | |
| print person.name | |
| person.name = "David" | |
| print person.name | |
| del(person.name) | |
| print person.name | |
| # Result: | |
| """ | |
| David | |
| Traceback (most recent call last): | |
| ... | |
| AttributeError: 'Person' object has no attribute '_name' | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment