Last active
December 17, 2015 01:59
-
-
Save sorcio/5532832 to your computer and use it in GitHub Desktop.
An implementation of Python properties akin to Python property() built-in for the purpose of showing descriptors.
It has some limitations: 1) it doesn't implement the del operation 2) decorator syntax can only be used for read-only properties. Example usage is included (see Foo class below). Read the full article: http://daviderizzo.com/2013/05/…
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
class PythonProperty(object): | |
""" | |
A property-like descriptor written in Python. | |
Simplifications from built-in property(): | |
- it doesn't implement the del operation | |
- decorator syntax can only be used for read-only properties | |
""" | |
def __init__(self, getter, setter=None): | |
# We need a function for the getter and one for the | |
# setter. setter could be None, in which case we | |
# would have a read-only property. | |
self._getter = getter | |
self._setter = setter | |
def __get__(self, instance, ownertype): | |
if instance: | |
# descriptor invoked from an instance | |
return self._getter(instance) | |
else: | |
# descriptor invoked from the owner class itself | |
return self | |
def __set__(self, instance, value): | |
if self._setter: | |
self._setter(instance, value) | |
else: | |
raise AttributeError('attribute is read-only') | |
class Foo(object): | |
# a read-only property | |
@PythonProperty | |
def trout(self): | |
return 'blub' | |
# a read-write property | |
def get_something(self): | |
"""getter function""" | |
return self._something | |
def set_something(self, value): | |
self._something = value | |
something = PythonProperty(get_something, set_something) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment