python print 打印对象问题

例如我需要 print 一个 FileNotFoundError 对象

print(e) # isinstance(e, FileNotFoundError) == true

会打印出如下信息
clipboard.png

但是我遍历这个对象的属性时,没有发现有这句话,那么这个 print 是如何输出这句信息的?

print('start')
    for i in dir(e):
        if (i != 'characters_written'):
            print(i, eval('e.'+ str(i)) )
print('end')

clipboard.png

阅读 5.8k
1 个回答
print的内容是取决于特殊方法 __repr__ 和 __str__的:
class A:
#再试下去掉注释
'''
def __str__(self):
    print("i am  in __str__ method")
    return "__str__"
'''
def __repr__(self):
    print("i am in __repr__ method")
    return "__repr__"

a = A()
print(a)
print(str(a))

试下交互模式:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
class A:
    def __str__(self):
        print("i am  in __str__ method")
        return "__str__"
    def __repr__(self):
        print("i am in __repr__ method")
        return "__repr__"
    
a = A()
a
Out[4]: i am in __repr__ method
__repr__

楼主可以再baidu下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题