def __repr__(self):
return '<%s %s (%s:%s) %s>' % (
self.__class__.__name__, self.urlconf_name, self.app_name,
self.namespace, self.regex.pattern)这种方法的意义/目的是什么?
发布于 2009-12-31 14:12:39
__repr__应该返回对象的可打印表示,这很可能是创建此对象的可能方法之一。请参阅官方文档here。__repr__更适合开发人员,而__str__更适合终端用户。
一个简单的例子:
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __repr__(self):
... return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)发布于 2009-12-31 14:11:47
这在Python documentation中得到了很好的解释
repr( object ):返回一个包含对象的可打印表示形式的字符串。这与转换(反向引号)产生的值相同。有时,能够像访问普通函数一样访问此操作是很有用的。对于许多类型,此函数尝试返回一个字符串,该字符串在传递给
eval()时将生成具有相同值的对象,否则表示为尖括号括起的字符串,其中包含对象类型的名称以及其他信息,通常包括对象的名称和地址。通过定义__repr__()方法,类可以控制此函数为其实例返回的内容。
因此,您在这里看到的是__repr__的默认实现,它对于序列化和调试很有用。
发布于 2016-11-16 02:03:05
独立的__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__。
Documentation,如果你愿意
https://stackoverflow.com/questions/1984162
复制相似问题