【问题标题】:Is there any way to create a class property in Python?有没有办法在 Python 中创建类属性?
【发布时间】:2011-01-11 12:09:18
【问题描述】:

以下由于某种原因不起作用:

>>> class foo(object):
...     @property
...     @classmethod
...     def bar(cls):
...             return "asdf"
... 
>>> foo.bar
<property object at 0x1da8d0>
>>> foo.bar + '\n'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'property' and 'str'

有没有办法做到这一点,还是我唯一的选择是诉诸某种元类诡计?

【问题讨论】:

标签: python class properties class-method


【解决方案1】:

如果您希望描述符property 在您从对象X 获取属性时触发,那么您必须将描述符放入type(X)。因此,如果 X 是一个类,则描述符必须进入该类的类型,也称为该类的元类——不涉及“诡计”,这只是一个完全通用的规则。

或者,您可以编写自己的专用描述符。请参阅here,了解关于描述符的出色“操作方法”条约。 编辑 例如:

class classprop(object):
  def __init__(self, f):
    self.f = classmethod(f)
  def __get__(self, *a):
    return self.f.__get__(*a)()

class buh(object):
  @classprop
  def bah(cls): return 23

print buh.bah

根据需要发出23

【讨论】:

  • 我在继承层次结构的其他地方使用元类,所以如果我使用元类,我会得到以下信息:metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
  • @Jason,您还可以使用所有涉及的元类的子类,如错误消息所述(很少使用多个自定义元类,或不使用子类 type 的元类,所以您可能只需要子类化您正在使用的一个自定义元类)——但如果自定义描述符完成了这项工作,它可能确实是一种更简单的方法。
猜你喜欢
  • 1970-01-01
  • 2016-08-25
  • 2022-09-22
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 2018-11-21
相关资源
最近更新 更多