有没有办法在Python中创建类属性?
由于某种原因,以下内容不起作用:
>>> 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'
有没有办法做到这一点,或者是我诉诸某种元类技巧的唯一选择?
The following doesn't work for some reason:
>>> 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'
Is there a way to do this, or is my only alternative to resort to some kind of metaclass trickery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望在从对象 X 获取属性时触发描述符
property
,则必须将该描述符放入type(X)
中。因此,如果 X 是一个类,则描述符必须位于该类的类型中,也称为该类的元类——不涉及“欺骗”,这只是一个完全通用的规则问题。或者,您可以编写自己的专用描述符。请参阅此处,了解有关描述符的出色“操作方法”条约。 编辑例如:
根据需要发出
23
。If you want the descriptor
property
to trigger when you get an attribute from object X, then you must put the descriptor intype(X)
. So if X is a class, the descriptor must go in the class's type, also known as the class's metaclass -- no "trickery" involved, it's just a matter of completely general rules.Alternatively, you might write your own special-purpose descriptor. See here for an excellent "how-to" treaty on descriptors. Edit for example:
emits
23
, as desired.