Skip to content

Instantly share code, notes, and snippets.

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):
def foo(cls):
return cls._foo
def foo(cls, value):
cls._foo = value
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)
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