由于某种原因,以下内容不起作用:
>>> 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'
有没有办法做到这一点,或者是我诉诸某种元类技巧的唯一选择?
如果你想要描述符property
当您从对象 X 获取属性时触发,则必须将描述符放入type(X)
。因此,如果 X 是一个类,则描述符必须位于该类的类型中,也称为该类的元类——不涉及“欺骗”,这只是一个完全通用的规则问题。
或者,您可以编写自己的专用描述符。看here一个关于描述符的优秀“操作方法”条约。Edit例如:
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
emits 23
, 如预期的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)