码迷,mamicode.com
首页 > 编程语言 > 详细

Python内置函数(53)——repr

时间:2016-11-14 01:48:09      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:函数返回   together   字符串表   pytho   util   name   nbsp   对象   close   

英文文档:

repr(object)
Return a string containing a printable representation of an object. 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.

 

说明:
  1. 函数功能返回一个对象的字符串表现形式。其功能和str函数比较类似,但是两者也有差异:函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式。
>>> a = some text
>>> str(a)
some text
>>> repr(a)
"‘some text‘"

  2. repr函数的结果一般能通过eval()求值的方法获取到原对象。

>>> eval(repr(a))
some text

  3. 对于一般的类型,对其实例调用repr函数返回的是其所属的类型和被定义的模块,以及内存地址组成的字符串。

>>> class Student:
    def __init__(self,name):
        self.name = name

>>> a = Student(Bob)
>>> repr(a)
<__main__.Student object at 0x037C4EB0>

  4. 如果要改变类型的repr函数显示信息,需要在类型中定义__repr__函数进行控制。

>>> class Student:
    def __init__(self,name):
        self.name = name
    def __repr__(self):
        return (a student named  + self.name)

>>> b = Student(Kim)
>>> repr(b)
a student named Kim

 

Python内置函数(53)——repr

标签:函数返回   together   字符串表   pytho   util   name   nbsp   对象   close   

原文地址:http://www.cnblogs.com/sesshoumaru/p/6060307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!