Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Per-class @property decorator in Python

Tags:

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
like image 976
Pablo Avatar asked Nov 15 '16 22:11

Pablo


1 Answers

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]

like image 51
Stephane Martin Avatar answered Sep 23 '22 02:09

Stephane Martin