如果 t.__str__() 返回非字符串,为什么 print(t) 错误,而不是 print(t.__str__()) ? [英] Why does print(t) error if t.__str__() returns a non-string, but not print(t.__str__())?

查看:29
本文介绍了如果 t.__str__() 返回非字符串,为什么 print(t) 错误,而不是 print(t.__str__()) ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 Python 中的 __str__ 方法.

I am trying to understand the __str__ method in Python.

class Test:
    def __str__(self):
        return 5

t = Test()

print(t.__str__())

在这个方法中它返回一个整数值,但打印方法能够打印它.

In this method it returns an integer value but the print method is able to print it.

但是,当我尝试 print(t) 时,它抛出了错误 TypeError: __str__ returned non-string (type int).

But, when I tried print(t) it threw the error TypeError: __str__ returned non-string (type int).

据我所知,print(t) 也在调用 __str__(self) 方法.

As I understand print(t) is also calling the __str__(self) method.

为什么 print(t.__str__()) 不需要字符串类型转换?

Why didn't print(t.__str__()) want the the string type conversion?

推荐答案

你所做的等同于 print(5),因为 print 调用了 print(5)code>__str__ on 5 获取字符串.但是传递对象时,print 调用对象上的 __str__ 并且没有得到一个实际的字符串作为响应.

What you’re doing is equivalent to print(5), which works because print calls __str__ on 5 to get a string. But passing the object, print calls __str__ on the object and doesn’t get an actual string in response.

这篇关于如果 t.__str__() 返回非字符串,为什么 print(t) 错误,而不是 print(t.__str__()) ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆