以下因某些原因无效:
>>> 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'
有没有办法做到这一点,或者是我唯一可以采用某种元类诡计的替代方法?
答案 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
。