Python中有没有不能转换为字符串的类型?

Lau*_*ndt 3 python type-conversion string-conversion

我可以在 Python 中将所有内容转换为字符串吗?

例如,这会抛出错误吗?

def test(arg):
    try:
       arg=str(arg)
    except ValueError:
Run Code Online (Sandbox Code Playgroud)

Pat*_*uta 5

标准库中的每种类型都可以使用该函数转换为Python中的字符串str()。然而,并不是 Python 中的每个对象都需要位于标准库中。

例如,以下类的实例TypeError在尝试将其转换为字符串时将抛出异常:

class O:
    def __str__(self):
        pass

o = O()
print(str(o))
# TypeError: __str__ returned non-string (type NoneType)
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为我们将默认__str__方法覆盖为不返回字符串的方法。