Python内置函数(53)——repr
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python内置函数(53)——repr相关的知识,希望对你有一定的参考价值。
英文文档:
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的主要内容,如果未能解决你的问题,请参考以下文章