Python的目的__

2024-03-28 10:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

def __repr__(self):
  return '<%s %s (%s:%s) %s>' % (
    self.__class__.__name__, self.urlconf_name, self.app_name,
    self.namespace, self.regex.pattern)

这种方法的意义/目的是什么?


Tags: 方法nameself目的appreturndefnamespace
3条回答

这在Python documentation中有很好的解释:

repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. 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.

所以您在这里看到的是^{}的默认实现,它对于序列化和调试非常有用。

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

独立Python解释器使用__repr__以可打印格式显示类。示例:

~> 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如果你愿意的话

相关问题 更多 >