gpt4 book ai didi

python - 如何将 `str.format` 直接用作 `__repr__` ?

转载 作者:太空狗 更新时间:2023-10-30 01:28:53 26 4
gpt4 key购买 nike

假设我想调试一个带有属性 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}" ) 上的绑定(bind)方法。因此,当调用代码尝试查找时,比如说 x.__repr__ (其中 x 是一个 SimpleClass 实例),Python 找到 __repr__ SimpleClass 的属性, 但随后无法将其识别为 SimpleClass方法 - 不遵守描述符协议(protocol)(字符串方法没有 __get__ 属性)。

似乎在 3.4 中,使用了 lambda会起作用,尽管我可以发誓它在以前的版本中必须是一个真正的功能。 functools.partial不管用。但无论如何你真的应该使用真正的功能。抱歉,它没有您想要的那么干。

关于python - 如何将 `str.format` 直接用作 `__repr__` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26378304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com