由于某些原因,以下内容不起作用:
>>> 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一个关于描述符的优秀“操作方法”条约。 编辑例如:
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
。
关于python - 有没有办法在 Python 中创建类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2173206/