首页 > 代码库 > Python内置函数(53)——repr
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。