Python中的每类@property装饰器

Pab*_*blo 6 python

Python为这样的实例支持@property装饰器:

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
Run Code Online (Sandbox Code Playgroud)

是否有可能为类具有类似的东西,以便行为是这样的(例如,与setter和getter方法一起):

class MyClass(object):
    _friend_stack = [1]

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

MyClass.current_friend # 1
Run Code Online (Sandbox Code Playgroud)

Ste*_*tin 8

在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]
Run Code Online (Sandbox Code Playgroud)

[疯狂的笑声跟着]

  • 从 3.5 版开始,这(使用元类)实际上是正确的[似乎是唯一的方法](https://mail.python.org/pipermail/python-ideas/2011-January/008959.html)。有一个 [open issue](https://bugs.python.org/issue24941) 关于添加 `classproperty` 装饰器,Erik Bray 建议编写纯 Python 版本是“微不足道的”。然而,[他的实现](https://mail.python.org/pipermail/python-ideas/2015-August/035349.html) 有点坏:正如 Nick Coghlan 指出的那样,通过类设置/删除属性将完全绕过描述符。 (3认同)