Pablo
Pablo

Reputation: 11021

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

Upvotes: 7

Views: 3404

Answers (1)

Stephane Martin
Stephane Martin

Reputation: 1642

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]

Upvotes: 8

Related Questions