__repr__
用于表示对象的开发者/解释器友好的表现形式,可能是一段有效的Python代码,当传递给eval()
时,可以重新创建一个相同的对象。来自Python文档:
object.repr(self)
由repr()内置函数和字符串转换(反引号)调用,计算对象的“官方”字符串表示。如果可能的话,这应该看起来像一个有效的Python表达式,可以在适当的环境中用于重新创建具有相同值的对象。如果不可能,应返回形式为<...some useful description...>的字符串。返回值必须是一个字符串对象。如果一个类定义了repr()但没有定义str(),那么在需要该类的实例的“非正式”字符串表示时也会使用repr()。
链接: https://docs.python.org/2/reference/datamodel.html#object.repr
E.g:
class tie(object):
def __init__(self, color):
self.color = color
t = tie('green')
repr(t) # prints <tie object at 0x10fdc4c10>
# can the default implementation be improved to tie(color='green')
# based on the parameters passed in the __init__ function
改变这个实现会面临哪些挑战,除了向后兼容/现有行为方面?
__repr __()
,例如基于类的__init __()
签名。 - glibdud<tie object at 0x10fdc4c10>
,而不是稍微努力一点生成tie(color='green')
。是否存在任何缺陷,导致通过查看__init__
参数来生成表示将完全错误? - 6haratdef __repr__(self): return "tie(color='{}')".format(self.color)
有什么问题? - stovflreturn "{0.__class__.__name__}({})".format(self, ", ".join('{}={}'.format(k,v) for k,v in self.__dict__.items())
。它可以处理像可变对象一样的东西,但这可能与构造函数参数无关。 - Bakuriu