python的class的__str__()和__repr__()函数
2016-11-29 14:36
435 查看
repr(object)
返回一个可以用来表示对象的可打印字符串
首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象
否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址)
一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。
str([object])
返回一个可以用来表示对象的可打印的友好的字符串.
对字符串,返回本身。
没有参数,则返回空字符串
对类,可通过 __str__() 成员控制其行为。该成员不存在,则使用其 __repr__() 成员。
与 repr 区别:不总是尝试生成一个传给 eval 的字符串,其目标是可打印字符串。
python2 中:
__repr__()
如前所述
__str__()
如前所述,返回字符串(字节流)
__unicode__()
返回unicode字符串
实现类时,应该实现 __unicode__(),然后提供了一个某种编码的 __str__()
def __str__(self): return unicode(self).encode('utf-8')
在python3中: __str__() 直接就是 unicode,字节流由__bytes__()提供。
相关文章推荐
- Python repr() 或str() 函数, 反引号
- Python repr() 函数和str() 函数
- Python中str()和repr()函数的区别
- Python内建函数str()和repr()
- python的str()和repr()函数比较
- python Class:面向对象高级编程 __str__ / __repr__
- python的class的__str__和__repr__(转)
- Python repr() 或str() 函数
- python的class的__str__和__repr__(转)
- Python repr() 或str() 函数(转)
- Python repr str 函数
- Python repr() 或str() 函数
- Python repr() 或str() 函数
- python基础---- __getattribute__----__str__,__repr__,__format__----__doc__----__module__和__class__
- Python repr() 或str() 函数
- python 内建函数 str() 和 repr() 的区别
- python 内建函数 str() 和 repr() 的区别
- Python repr() 或str() 函数
- python 内建函数 str() 和 repr() 的区别
- Python菜鸟晋级03----repr() 与str() 函数的区别