当print 实例化对象的时候,可以直接输出__str__ 中的 return结果
在console中 直接输实例对象c 只能输出<__main__.Cycle object at 0x00000000057671D0> 似乎__str__() 不会被调用 可见__str__对于用户相对友好
而当print c的时候 可以直接输出return的结果
>>> class Cycle(object): def __init__(self,x): self.x=x def __str__(self): return "{0}".format(self.x) >>> c=Cycle(2) >>> c <__main__.Cycle object at 0x00000000057671D0> >>> print c 2 >>> ================================ RESTART ================================ >>> (1,1,7) >>>
当使用__repr__的时候 无论是直接输出c 还是 print c 都能得到retrun中的字符串结果 可见__repr__对于开发人员更友好
>>> class Cycle(object): def __init__(self,x): self.x=x def __repr__(self): return "{0}".format(self.x) >>> c=Cycle(1) >>> c 1 >>> print c 1
总结:
__str__()用于显示给用户,而__repr__()用于显示给开发人员