问题:Python __repr__的目的

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

此方法的意义/目的是什么?

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

What is the significance/purpose of this method?


回答 0

__repr__应该返回对象的可打印表示形式,这很可能是创建该对象的一种可能方式。请参阅此处的官方文档。__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)

__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See official documentation here. __repr__ is more for developers while __str__ is for end users.

A simple example:

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

回答 1

Python文档中对此进行了很好的解释:

reprobject):返回一个字符串,其中包含对象的可打印表示形式。这与转换(反引号)产生的值相同。能够以普通功能访问此操作有时很有用。对于许多类型,此函数会尝试返回一个字符串,该字符串将在传递给时产生一个具有相同值的对象eval(),否则表示形式是一个用尖括号括起来的字符串,其中包含对象类型的名称以及其他信息通常包括对象的名称和地址。类可以通过定义__repr__()方法来控制此函数为其实例返回的内容。

因此,您在这里看到的是的默认实现__repr__,这对于序列化和调试很有用。

This is explained quite well in the 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.

So what you’re seeing here is the default implementation of __repr__, which is useful for serialization and debugging.


回答 2

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


文档,如果需要的话

__repr__ is used by the standalone Python interpreter to display a class in printable format. Example:

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

In cases where a __str__ method is not defined in the class, it will call the __repr__ function in an attempt to create a printable representation.

>>> str(demo)
'<StackOverflow demo object __repr__>'

Additionally, print()ing the class will call __str__ by default.


Documentation, if you please


回答 3

__repr__方法简单地告诉Python的打印类对象

The __repr__ method simply tells Python how to print objects of a class


回答 4

查看它们之间差异的示例(我从此复制),

>>> x=4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y='stringy'
>>> repr(y)
"'stringy'"
>>> str(y)
'stringy'

的回报repr()str()是相同的int x,但有一个为返回值之间的差异str y-一个是正式的,另一个是非正式的。形式表示和非正式表示之间最重要的区别之一是,__repr__str值的默认实现可以称为eval的参数,而返回值将是有效的字符串对象,如下所示:

>>> repr(y)
"'a string'"
>>> y2=eval(repr(y))
>>> y==y2
True

如果您尝试将返回值__str__作为eval的参数调用,则结果将无效。

An example to see the differences between them (I copied from this source),

>>> x=4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y='stringy'
>>> repr(y)
"'stringy'"
>>> str(y)
'stringy'

The returns of repr() and str() are identical for int x, but there’s a difference between the return values for str y — one is formal and the other is informal. One of the most important differences between the formal and informal representations is that the default implementation of __repr__ for a str value can be called as an argument to eval, and the return value would be a valid string object, like this:

>>> repr(y)
"'a string'"
>>> y2=eval(repr(y))
>>> y==y2
True

If you try to call the return value of __str__ as an argument to eval, the result won’t be valid.


回答 5

当我们通过定义类来创建新类型时,我们可以利用Python的某些功能使新类易于使用。这些功能之一是“特殊方法”,也称为“魔术方法”。

特殊方法的名称以两个下划线开头和结尾。我们定义它们,但通常不直接按名称调用它们。而是在特定情况下自动执行。

能够通过使用print语句输出对象实例的值很方便。当我们这样做时,我们希望该值以某种可以理解的明确格式表示在输出中。该再版特殊方法可用于安排要做到这一点。如果定义此方法,则在打印为其定义了该方法的类的实例的值时可以自动调用它。但是,应该提到的是,还有一个str特殊方法,用于相似但不相同的目的,如果我们也定义了它,则该方法可以优先。

如果尚未定义,则为Point3D类的repr方法,并将my_point实例化为Point3D的实例,然后执行此操作…

打印my_point …我们可能会将其视为输出…

不是很好,是吗?

因此,我们定义了reprstr特殊方法,或同时定义了两者,以获得更好的输出。

**class Point3D(object):
    def __init__(self,a,b,c):
        self.x = a
        self.y = b
        self.z = c
    def __repr__(self):
        return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
    def __str__(self):
        return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point # __repr__ gets called automatically
print my_point # __str__ gets called automatically**

输出…

(1,2,3)(1,2,3)

When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is “special methods”, also referred to as “magic methods”.

Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.

It is convenient to be able to output the value of an instance of an object by using a print statement. When we do this, we would like the value to be represented in the output in some understandable unambiguous format. The repr special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we print the value of an instance of a class for which we defined this method. It should be mentioned, though, that there is also a str special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.

If we have not defined, the repr method for the Point3D class, and have instantiated my_point as an instance of Point3D, and then we do this …

print my_point … we may see this as the output …

Not very nice, eh?

So, we define the repr or str special method, or both, to get better output.

**class Point3D(object):
    def __init__(self,a,b,c):
        self.x = a
        self.y = b
        self.z = c
    def __repr__(self):
        return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
    def __str__(self):
        return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point # __repr__ gets called automatically
print my_point # __str__ gets called automatically**

Output …

(1, 2, 3) (1, 2, 3)


回答 6

为您实现的每个类实现repr。不应有任何借口。为您认为易读性对非歧义性更为重要的类实施str

请参考以下链接:https://www.pythoncentral.io/what-is-the-difference-between- STR -和- 再版 -in的Python /

Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.

Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。