Skip to content

Instantly share code, notes, and snippets.

@dmiro
Created May 21, 2014 13:58
Show Gist options
  • Select an option

  • Save dmiro/5dd86caa36b38120eadf to your computer and use it in GitHub Desktop.

Select an option

Save dmiro/5dd86caa36b38120eadf to your computer and use it in GitHub Desktop.
Python property class
"""
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