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

Python的两个魔法方法:__repr__和__str__目录例子关系使用官方文档参考 repr 和 str 是 Python 的两个魔法方法 Magic Specialmetho 更多魔法方法可以参考 AGuidetoPyth sMagicMethod 以及 Specialmetho 提前说明下面的 str 和 repr 都是 Python 中的内置函数 分别

目录

例子

关系

使用

官方文档

参考


__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 ‘

‘ 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__ 方法。

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

 

使用

在 SO 上的解释是:

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

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

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

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

上表是来自 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/

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

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

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

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/208355.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 上午11:46
下一篇 2026年3月19日 上午11:46


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号