【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
从上面例子可以看出,当打印strtest的一个实例st的时候,__str__函数被调用到。
其实,python里面的对象基本上都默认有个__str__供print函数所用。比如字典里的__str__,见红色部分:
【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…………………………………………………………………………
相关文章推荐
- 【ZZ】python - __str__ 和 __repr__
- 区别python 的str和repr
- Python repr() 或str() 函数
- Python的str()和repr()
- python - __str__ 和 __repr__
- python中str和repr区别
- Python的repr和str有什么不同?
- python print str repr pprint
- python的str()和repr()的区别
- 飘逸的python - str vs. repr
- str和repr区别 分类: python学习 2014-06-23 10:05 205人阅读 评论(0) 收藏
- python中的repr与str
- Python的repr和str有什么不同?
- Python repr() str() print %r
- python的str()和repr()的区别
- python str与repr的区别
- python - __str__ 和 __repr__
- python中str()和repr()区别
- python str和repr的区别
- python __str__ , __repr__区别