Pablo Pablo - 23 days ago 6
Python Question

Per-class @property decorator in Python

Python supports a @property decorator for instances like so:

class MyClass(object):
def __init__(self):
self._friend_stack = [1]
@property
def current_friend(self):
return self._friend_stack[0]

myobj = MyClass()
myobj.current_friend # 1


Is it possible to have something like this for classes, so that the behavior is something like this (along with setter and getter methods, for instance):

class MyClass(object):
_friend_stack = [1]

@property
def current_friend(cls):
return cls._friend_stack[0]

MyClass.current_friend # 1

Answer

In Python 3:

class MyMeta(type):
    def current_friend(cls):
        return cls._friend_stack[0]
    current_friend = property(current_friend)

class MyClass(metaclass=MyMeta):
    _friend_stack = [1]

[mad laugh follows]