您的位置:首页 > 编程语言 > Python开发

【ZZ】python - __str__ 和 __repr__

2014-05-23 12:31 246 查看
详细页面: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…………………………………………………………………………
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: