简体   繁体   English

我如何直接使用`str.format`作为`__repr__`?

[英]How can I use `str.format` directly as `__repr__`?

Say I want to debug a simple class with an attribute myattribute . 假设我想调试一个带有属性myattribute的简单类。 I create a repr method like this: 我创建一个这样的repr方法:

class SimpleClass:
  def __repr__(self):
    return "{0.myattribute}".format(self)

It feels a bit redundant, so I would prefer to use format directly: 感觉有点多余,所以我更喜欢直接使用format

class SimpleClass:
  __repr__ = "{0.myattribute}".format

...but that fails with an IndexError: tuple index out of range . ...但是因为IndexError: tuple index out of range而失败。 I understand it that format cannot access the self argument, but I do not see why. 我理解format无法访问self参数,但我不明白为什么。

Am I doing something wrong, is this a CPython limitation – or what else? 我做错了什么,这是CPython限制 - 或者还有什么?

"{0.myattribute}".format is already a bound method on the string object ( "{0.myattribute}" ). "{0.myattribute}".format已经是字符串对象( "{0.myattribute}" )的绑定方法。 So when the calling code attempts to look up, say, x.__repr__ (where x is a SimpleClass instance), Python finds the __repr__ attribute of SimpleClass , but then cannot recognize it as a SimpleClass method - the descriptor protocol is not honoured (the string method has no __get__ attribute). 因此,当调用代码试图查找时,例如x.__repr__ (其中xSimpleClass实例),Python找到SimpleClass__repr__属性,但是后来无法将其识别为SimpleClass方法 - 描述符协议不受尊重( string方法没有__get__属性)。

It appears that in 3.4, using a lambda will work, although I could have sworn it had to be a real function in previous versions. 似乎在3.4中,使用lambda会起作用,虽然我可以发誓它必须是以前版本中的真正功能。 functools.partial will not work. functools.partial不起作用。 But you really should be using a real function anyway. 但无论如何你真的应该使用真正的功能。 Sorry it's not as DRY as you'd like. 对不起它不像你想的那么干。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM