__repr__与__str__
来源:互联网 发布:ip扫描软件 编辑:程序博客网 时间:2024/06/05 19:29
这两者主要是用来显示、打印对象。那么他们有什么区别和关联呢。
首先说下str()和repr内建函数,概括的说str()返回值是给人看的,repr()是给机器看的,而repr()函数得到的字符串通常可以用来重新获得该对象,通常情况下 obj==eval(repr(obj)) 这个等式是成立的。str()会调用__str__,repr()会调用__repr__。对于打印操作会尝试使用__str__,但是如果没有这个函数则会尝试使用__repr__。对于类来说其他的地方都是使用__repr__,比如getattr(obj,attr)。
看下面这个例子
>>> class b:... def __init__(self):... self.x='1'... def doit(self):... print self.x... def __repr__(self):... return self.__attrnames()... def __attrnames(self):... result = ''... for attr in dir(self):... result+='\n%s=%s' %(attr,getattr(self,attr))... return result... >>> ab = b()>>> ab当我们在交互模式输入ab的时候,他会尝试调用__repr__方法,在上面的代码中__repr__又会调用__attrnames方法,而__attrnames中使用了getattr(self,attr),当参数attr是__init__等方法时,getattr会尝试调用__repr__方法,这样就形成了一个循环。
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames File "<stdin>", line 7, in __repr__ File "<stdin>", line 11, in __attrnames处理这个问题的方式就是用__str__替换__repr__就可以了。
0 0
- __repr__与__str__
- __str__与 __repr__
- Python 3 str()与repr()、__str__与__repr__:
- python - __str__ 和 __repr__
- python __str__ , __repr__区别
- python - __str__ 和 __repr__
- python - __str__ 和 __repr__
- __str__ 和 __repr__
- python - __str__ 和 __repr__
- [Python]Compare __repr__ & __str__
- python __str__,__repr__,__call__()
- python __str__ 和 __repr__
- __str__和__repr__比较
- __str__()和__repr__()的调用
- 【ZZ】python - __str__ 和 __repr__
- __repr__和__str__的区别
- python中 __str__和__repr__
- Python中__str__和__repr__
- NY25 A Famous Music Composer
- adaboost学习
- CSS自适应布局(左右固定 中间自适应或者右侧固定 左侧自适应)
- 除法运算的注意点
- HDU 1875(最小生成树)
- __repr__与__str__
- POJ2406 KMP前缀周期
- java并发编程(5)--多个线程共享数据和对象的方式
- Deep Learning in NLP(一)
- DRP学习总结
- C++学习笔记3--作用域 构造析构器 访问控制 友元关系
- 累计概率霍夫变换(ProgressiveProbabilistic Hough Trans
- POJ 2752 同一个串的前后串
- 动态规划之最长公共子序列