如果我用它自己的 __str__()
函数定义一个类,str(a)
是否等同于 a.__str__()
, a
是我的类的一个实例吗?
我检查了 python doc , 它没有明确说明是这种情况。
最佳答案
简短回答:是的!
根据Python docs (我突出了相关部分):
object.__str__(self)
Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.
This method differs from
object.__repr__()
in that there is no expectation that__str__()
return a valid Python expression: a more convenient or concise representation can be used.The default implementation defined by the built-in type object calls
object.__repr__()
.
因此 your_instance.__str__
通常在您执行 str(your_instance)
时被调用。
更长的答案:对于“特殊方法”(带有两个前导下划线和两个尾随下划线的方法)有一个异常(exception),因为它们是在类而不是实例中查找的。所以 str(a)
实际上是 type(a).__str__(a)
而不是 a.__str__()
。但在大多数情况下,它们是相同的,因为很少有人会在实例上覆盖类的方法。尤其不是特殊方法。
另见 relevant documentation on "Special method lookup" :
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.
就像 @zzh1996 在评论中指出的那样,即使实例具有自定义可调用的 __str__
属性,以下代码也将使用类上定义的方法:
>>> class A(object):
... def __str__(self):
... return 'a'
>>> instance = A()
>>> instance.__str__ = lambda: 'b'
>>> str(instance)
'a'
>>> instance.__str__()
'b'
关于python - python `str()`函数是否调用类的 `__str__()`函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41168899/