Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created December 13, 2012 20:48
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mhulse/4279705 to your computer and use it in GitHub Desktop.
Simple Python accessors (@getter/@Setter and @deleter) example/test using mixin and decorators... I'm using Python 2.6 for testing.
import pprint
# pprint.pprint(dir(obj))
# pprint.pprint(list)
# $ python manage.py runscript am_script2
class BaseMixin(object):
#----------------------------------
# Init:
#----------------------------------
def __init__(self):
# Default value:
self._x = None
#----------------------------------
# Accessors:
#----------------------------------
@property
def x(self):
"I'm the 'x' property."
# Return the value of x:
return self._x
@x.setter
def x(self, value):
# Set the value of x:
self._x = value
@x.deleter
def x(self):
# Delete the value of x:
del self._x
class Foo(BaseMixin):
# What to do here?
pass
def run():
# Instanciate:
f = Foo()
# Set:
f.x = 'Dogs!'
# Interrogate:
pprint.pprint(dir(f))
pprint.pprint(dir(f.x))
# Get:
print f.x
# Delete:
del(f.x)
#print f.x # AttributeError: 'Foo' object has no attribute '_x'
$ python manage.py runscript am_script2
['__class__',
'__delattr__',
'__dict__',
'__doc__',
'__format__',
'__getattribute__',
'__hash__',
'__init__',
'__module__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_x',
'x']
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getslice__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'_formatter_field_name_split',
'_formatter_parser',
'capitalize',
'center',
'count',
'decode',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'index',
'isalnum',
'isalpha',
'isdigit',
'islower',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
Dogs!
@mhulse
Copy link
Author

mhulse commented Dec 14, 2012

"Discussion" here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment