有没有办法在Python中创建一个类属性?

时间:2010-01-31 20:36:29

标签: python class properties class-method

以下因某些原因无效:

>>> 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'

有没有办法做到这一点,或者是我唯一可以采用某种元类诡计的替代方法?

1 个答案:

答案 0 :(得分:6)

如果希望在从对象X获取属性时触发描述符property,则必须将描述符放在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