__str__简单用法

class TestStrRepr(object):
    def __str__(self):
        return "good, this is TestStr"  #必须返回字符串
  print TestStr() #good, this is TestStr

可以认为__str__的目的是为print 这样的打印函数调用而设计的,当print 一个对象时,会自动调用其__str__方法

而repr 函数则是将对象转换为字符串显示

a = "hello"

repr(a) # "'hello'"

repr([1,2,3]) #'[1,2,3]'

原文地址:https://www.cnblogs.com/bjdxy/p/2766493.html