Per-class @property decorator in Python

Python supports the @property decorator for such cases:

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 the behavior is similar to this (along with the setter and getter methods, for example):

class MyClass(object):
    _friend_stack = [1]

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

MyClass.current_friend # 1
+4
source share
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]

[crazy laugh follows]

+4
source

Source: https://habr.com/ru/post/1660871/


All Articles