1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5     def __repr__(self):
 6         return 'this is repr'
 7     # def __str__(self):
 8     #     return 'this is str'
 9 f1=Foo('cy',23)
10 print(f1)   #str(f1)-->f1.__str__()

输出

this is repr

 

 

st函数或者print函数--->obj.__str__()

repr函数或者交互式解释器--->obj.__repr__()

如果__str__没被定义,那就使用__repr__来代替输出

str和repr返回的必须是字符串,否则抛出异常

收藏 打印