【ZZ】python - __str__ 和 __repr__

详细页面:http://www.verydemo.com/demo_c122_i31216.html

【http://blog.csdn.net/followingturing/article/details/7954204】

__str__ 直接打印对象的实现方法


在python语言里,__str__一般是格式是这样的。

class A:

       def __str__(self):

              return "this is in str"

事实上,__str__是被print函数调用的,一般都是return一个什么东西。这个东西应该是以字符串的形式表现的。如果不是要用str()函数转换。当你打印一个类的时候,那么print首先调用的就是类里面的定义的__str__,比如:str.py

#!/usr/bin/env python
                                                                                                                                                                                 
class strtest:
    def __init__(self):
        print "init: this is only test"
    def __str__(self):
        return "str: this is only test"

if __name__ == "__main__":
    st=strtest()
    print st
$./str.py
init: this is only test

str: this is only test
从上面例子可以看出,当打印strtest的一个实例st的时候,__str__函数被调用到。

其实,python里面的对象基本上都默认有个__str__供print函数所用。比如字典里的__str__,见红色部分:
>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt…………………………………………………………………………
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值