Does python `str()` function call `__str__()` function of a class?
如果我用自己的
我检查了python文档,它没有明确地说明这是事实。
简短回答:是的!
根据python文档(我突出显示了相关部分):
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__() .
所以当你做
更长的答案:对于"特殊方法"(带有两个前导下划线和两个尾随下划线的方法),有一个异常,因为这些方法是在类上查找的,而不是在实例上查找的。所以
另请参见"特殊方法查找"的相关文档:
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在注释中指出的那样,以下代码将使用类上定义的方法,即使实例具有自定义的可调用
1 2 3 4 5 6 7 8 9 | >>> class A(object): ... def __str__(self): ... return 'a' >>> instance = A() >>> instance.__str__ = lambda: 'b' >>> str(instance) 'a' >>> instance.__str__() 'b' |
是的,是的。请看下面的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> class A: ... def __init__(self, a): ... self.a = a ... def __str__(self): ... print"Inside __str__" ... return self.a ... >>> >>> a = A('obj1') >>> a <__main__.A instance at 0x0000000002605548> >>> >>> a.__str__() Inside __str__ 'obj1' >>> >>> str(a) Inside __str__ 'obj1' |
根据
object.__str__(self) Called by
str(object) and the built-in functions
format() andprint() to compute the"informal" or nicely printable
string representation of an object. The return value must be a string
object.
是的,但也在印刷品上。参见文档https://docs.python.org/2/reference/datamodel.html object.str