Python的两个魔法方法:__repr__和__str__

目录

例子

关系

使用

官方文档

参考


__repr____str__ 是 Python 的两个魔法方法(Magic/Special method),更多魔法方法可以参考 A Guide to Python's Magic Methods 以及 Special method names

 

提前说明下面的 str() 和 repr() 都是 Python 中的内置函数,分别调用 __str__() 和 __repr__()。至于内置函数的源码实现可以参考 Finding the source code for built-in Python functions?

 

例子

>>> class A:
	pass

>>> a1 = A()
>>> print(repr(a1))
<__main__.A object at 0x0000000003166EB8>

>>> print(str(a1))
<__main__.A object at 0x0000000003166EB8>


这里的 0x0000000003166EB8 是什么呢?我们可以用 hex(id(a1)) 方法验证一下,发现结果和它是相同的。说明这就是 a1 对象的 id。更具体一点:

CPython implementation detail: For CPython, id(x) is the memory address where x is stored.

 可以参考:In Python, what does '<function at …>' mean?

 

>>> class A:
	def __str__(self):
                #__str__使用:被打印的时候需要以字符串的形式输出的时候,就会找到这个方法,并将返回值打印出来
		return "我是一个字符串"                                                                      
# 要想显示对象的属性,可以
# (1)return 后加上你想要格式化输出的属性,比如: return "%d %s" % (int("123"), str(123))                                                                   
# (2)利用字符串的format方法,比如:"{},{}".format(1,2)	
>>> a1 = A()
>>> print(repr(a1))
<__main__.A object at 0x00000000033712E8>

>>> print(str(a1))
我是一个字符串

与下例对比

 

>>> class A:
	def __repr__(self):   #返回一个可以用来表示对象的可打印字符串
		return "我是一个字符串"

	
>>> a1 = A()
>>> print(repr(a1))
我是一个字符串

>>> print(str(a1))
我是一个字符串

 此例表明 __str__ 方法默认调用了 __repr__ 方法。

 

关系

__str__ 方法其实调用了 __repr__ 方法。

 

使用

SO 上的解释是:

__repr__ 目的是为了表示清楚,是为开发者准备的。

__str__ 目的是可读性好,是为使用者准备的。

我的理解是 __repr__ 应该尽可能的表示出一个对象来源的类以及继承关系,方便程序员们了解这个对象。而 __str__ 就简单的表示对象,而不要让不懂编程的以为输出的是 bug。

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2012-03-14 09:21:58.130922'
>>> repr(today)
'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'

上表是来自 bitoffdev 的回答。

我们可以看到 str(today) 输出的很正常,哪个都看得懂。但是 repr(today) 的输出对不懂编程的就来说有点奇怪了,只懂一丢丢的还可能会以为自己搞出了啥幺蛾子呢。但是这对于有点经验的人来说这个就表示 today 对象是由 datetime 类实例化出来的。

 

官方文档

object.__repr__(self)

Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some usefuldescription...> should be returned. The return value must be a string object. If a class defines __repr__()but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

 

object.__str__(self)

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

The default implementation defined by the built-in type object calls object.__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.

 

str(object='')

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, ''.

 

参考

http://blog.csdn.net/luckytanggu/article/details/53649156

https://www.cnblogs.com/superxuezhazha/p/5746922.html

http://blog.csdn.net/DucklikeJAVA/article/details/73478307

https://docs.python.org/3/library/functions.html

https://docs.python.org/3/reference/datamodel.html

 

  • 51
    点赞
  • 96
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值