【问题标题】:Per-class @property decorator in PythonPython中的每类@property装饰器
【发布时间】:2016-11-15 22:58:45
【问题描述】:

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

类是否可以有这样的东西,所以行为是这样的(例如,连同 setter 和 getter 方法):

class MyClass(object):
    _friend_stack = [1]

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

MyClass.current_friend # 1

【问题讨论】:

  • 想你想要@classmethod
  • @classmethod 允许我做MyClass.current_friend(),但不允许我做MyClass.current_friend = 2。我想要后一种行为。我还希望有机会在访问变量时运行代码。
  • 你能展示一个类属性有用的虚构用例吗?大多数属性都依赖self 在幕后做一些事情。

标签: python


【解决方案1】:

在 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]

[疯狂的笑声]

【讨论】:

  • 这(使用元类)实际上是正确的,seemingly only way to do it 从 3.5 版开始。有一个 open issue 关于添加 classproperty 装饰器,Erik Bray 建议编写纯 Python 版本是“微不足道的”。但是,his implementation 有点坏了:正如 Nick Coghlan 指出的那样,通过类设置/删除属性将完全绕过描述符。
  • 请参考文档中的任何内容?需要阅读更多内容。
猜你喜欢
  • 2017-01-25
  • 2016-03-14
  • 2013-01-19
  • 2022-01-18
  • 2019-09-20
  • 2010-10-14
相关资源
最近更新 更多