python中的__str__和__repr__方法

如果要把一个类的实例变成 str,就需要实现特殊方法__str__():

class A(object):
def __init__(self,name,age):
self.name=name
self.age=age

def __str__(self):
return "this is __str__"
def __repr__(self):
return "this is __repr__"

如果类中没有str和repr方法,打印实例化对象a会得到:<__main__.A object at 0x0000016D7FB1F9B0>

如果定义了,在交互模式中打印:

>>> a=A('OK',18)
>>> a
this is __repr__
>>> print(a)
this is __str__
>>>

因为 Python 定义了__str__()和__repr__()两种方法,__str__()用于显示给用户,而__repr__()用于显示给开发人员。

如果类中只定义了repr却没有str方法,print(a)也会打印repr的结果。

猜你喜欢

转载自www.cnblogs.com/pfeiliu/p/11908033.html