Created
January 4, 2012 19:20
-
-
Save josiahcarlson/1561563 to your computer and use it in GitHub Desktop.
Get properties... on classes!
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
''' | |
Written January 4, 2012 by Josiah Carlson | |
Released into the public domain. | |
I've only ever needed this once, but I had to learn the descriptor protocol. | |
Works just like a property, except that what you decorate gets the class | |
instead of the instance. | |
class Example(object): | |
@ClassProperty | |
def foo(cls): | |
return cls._foo | |
@foo.setter | |
def foo(cls, value): | |
cls._foo = value | |
@foo.deleter | |
def foo(cls): | |
del cls._foo | |
''' | |
class ClassProperty(object): | |
def __init__(self, get, set=None, delete=None): | |
self.get = get | |
self.set = set | |
self.delete = delete | |
def __get__(self, obj, cls=None): | |
if cls is None: | |
cls = type(obj) | |
return self.get(cls) | |
def __set__(self, obj, value): | |
cls = type(obj) | |
self.set(cls, value) | |
def __delete__(self, obj): | |
cls = type(obj) | |
self.delete(cls) | |
def getter(self, get): | |
return ClassProperty(get, self.set, self.delete) | |
def setter(self, set): | |
return ClassProperty(self.get, set, self.delete) | |
def deleter(self, delete): | |
return ClassProperty(self.get, self.set, delete) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment