Chinaunix首页 | 论坛 | 博客
  • 博客访问: 89899
  • 博文数量: 30
  • 博客积分: 1501
  • 博客等级: 上尉
  • 技术积分: 300
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-01 09:23
文章分类

全部博文(30)

文章存档

2011年(6)

2010年(24)

分类: Python/Ruby

2011-02-10 16:42:43

repr
repr(object)

返回一个可以用来表示对象的可打印字符串

首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象
否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址)
一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。

Python 手册:

Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method.

str
str([object])

返回一个可以用来表示对象的可打印的友好的字符串

对字符串,返回本身。
没有参数,则返回空字符串
对类,可通过 __str__() 成员控制其行为。该成员不存在,则使用其 __repr__() 成员。

与 repr 区别:不总是尝试生成一个传给 eval 的字符串,其目标是可打印字符串。

Python 手册:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, .


其他
python2 中:

__repr__()
 如前所述
 
__str__()
 如前所述,返回字符串(字节流)
 
__unicode__()
 返回unicode字符串
 

实现类时,应该实现 __unicode__(),然后提供了一个某种编码的 __str__()


def __str__(self):    return unicode(self).encode('utf-8')
在python3中: __str__() 直接就是 unicode,字节流由__bytes__()提供。

参考



 

阅读(5075) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~