__repr__ 方法的作用是什么?
def __repr__(self):
return '<%s %s (%s:%s) %s>' % (
self.__class__.__name__, self.urlconf_name, self.app_name,
self.namespace, self.regex.pattern)
这个方法有什么重要性或者目的呢?
6 个回答
20
__repr__
是 Python 解释器用来以可打印的格式显示一个类的内容的。举个例子:
~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
... def __init__(self):
... pass
... def __repr__(self):
... return '<StackOverflow demo object __repr__>'
...
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>
如果一个类里没有定义 __str__
方法,解释器会尝试调用 __repr__
函数来生成一个可打印的表示。
>>> str(demo)
'<StackOverflow demo object __repr__>'
另外,使用 print()
打印这个类时,默认会调用 __str__
方法。
文档链接,请查阅
233
__repr__
这个东西应该返回一个可以打印出来的对象表示,通常是创建这个对象的某种方式。你可以在官方文档中查看详细信息 这里。__repr__
更偏向于开发者使用,而 __str__
则是给普通用户用的。
下面是一个简单的例子:
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __repr__(self):
... cls = self.__class__.__name__
... return f'{cls}(x={self.x!r}, y={self.y!r})'
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)