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)
有没有办法做到这一点,或者是我唯一可以采用某种元类技巧的替代方案?
如果希望在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
根据需要发出.
归档时间: |
|
查看次数: |
657 次 |
最近记录: |