__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]'

posted @ 2012-11-12 16:07  践道者  阅读(822)  评论(0编辑  收藏  举报