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

Jas*_*ker 8 python properties class 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'
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lli 6

如果希望在property从对象X获取属性时触发描述符,则必须将描述符放入type(X).因此,如果X是一个类,那么描述符必须在类的类型中,也就是类的元类 - 不涉及"欺骗",这只是完全一般规则的问题.

或者,您可以编写自己的专用描述符.请参阅此处,了解有关描述符的优秀"操作方法"条约. 编辑例如:

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

23根据需要发出.