Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get properties... on classes!
'''
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
You can’t perform that action at this time.