python - python `str()`函数是否调用类的 `__str__()`函数?

标签 python string class

如果我用它自己的 __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/

相关文章:

php - 正则表达式匹配某些标签之外的所有换行符

string - 如何将字符串 "[1, 2, 3]"转换为 Vec<u8>?

python - 如何在 Python 中迭代一个 Unicode 字符串?

string - 将字符串转换为二进制字符串表示的有效方法

c++ - C++ 中的运算符重载和符号

JavaScript:如何在父类的构造函数中获取子类的方法?

python - 财经新闻的机器学习

python - 错误文件未打开以供读取

python - 检查成员变量是否由构造函数初始化?

python - 如何使用 python 成像库创建位图