[英]How do I use __str__() and __repr__() for a singly linked list in Python 3.6?
[英]How can I use `str.format` directly as `__repr__`?
假设我想调试一个带有属性myattribute
的简单类。 我创建一个这样的repr
方法:
class SimpleClass:
def __repr__(self):
return "{0.myattribute}".format(self)
感觉有点多余,所以我更喜欢直接使用format
:
class SimpleClass:
__repr__ = "{0.myattribute}".format
...但是因为IndexError: tuple index out of range
而失败。 我理解format
无法访问self
参数,但我不明白为什么。
我做错了什么,这是CPython限制 - 或者还有什么?
"{0.myattribute}".format
已经是字符串对象( "{0.myattribute}"
)的绑定方法。 因此,当调用代码试图查找时,例如x.__repr__
(其中x
是SimpleClass
实例),Python找到SimpleClass
的__repr__
属性,但是后来无法将其识别为SimpleClass
方法 - 描述符协议不受尊重( string方法没有__get__
属性)。
似乎在3.4中,使用lambda
会起作用,虽然我可以发誓它必须是以前版本中的真正功能。 functools.partial
不起作用。 但无论如何你真的应该使用真正的功能。 对不起它不像你想的那么干。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.