Created
January 18, 2016 12:34
-
-
Save wuftymerguftyguff/41b4ab5b2275c4fd973a to your computer and use it in GitHub Desktop.
Python descriptor aide memoir - Custom getter server for dynamic attributes
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
class Person(object): | |
def addProperty(self, attribute): | |
# create local setter and getter with a particular attribute name | |
getter = lambda self: self._getProperty(attribute) | |
setter = lambda self, value: self._setProperty(attribute, value) | |
# construct property attribute and add it to the class | |
setattr(self.__class__, attribute, property(fget=getter, \ | |
fset=setter, \ | |
doc="Auto-generated method")) | |
def _setProperty(self, attribute, value): | |
print "Setting: %s = %s" %(attribute, value) | |
setattr(self, '_' + attribute, value.title()) | |
def _getProperty(self, attribute): | |
print "Getting: %s" %attribute | |
return getattr(self, '_' + attribute) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment