问题描述
下面语句中%r
是什么意思?
print '%r' % (1)
我想我听说过 %s
、%d
和 %f
但从未听说过这个.
背景:
在 Python 中,有两个内置函数可以将对象转换为字符串:str
与 代表
.str
应该是一个友好的、人类可读的字符串.repr
应该包含有关对象内容的详细信息(有时,它们会返回相同的内容,例如对于整数).按照惯例,如果有一个 Python 表达式将评估为另一个 == 对象,repr
将返回这样的表达式,例如
如果返回一个表达式对一个对象没有意义,repr
应该返回一个由 < 包围的字符串.和 > 符号,例如.
回答您最初的问题:
另外:
您可以通过实现 __str__
和 __repr__
方法.
Foo 类:def __init__(self, foo):self.foo = foodef __eq__(自我,其他):"""实现 ==."""返回 self.foo == other.foodef __repr__(self):# 如果你评估这个函数的返回值,# 你会得到另一个 Foo 实例,它是 == 到 self返回 "Foo(%r)" % self.foo
What's the meaning of %r
in the following statement?
print '%r' % (1)
I think I've heard of %s
, %d
, and %f
but never heard of this.
Background:
In Python, there are two builtin functions for turning an object into a string: str
vs. repr
. str
is supposed to be a friendly, human readable string. repr
is supposed to include detailed information about an object's contents (sometimes, they'll return the same thing, such as for integers). By convention, if there's a Python expression that will eval to another object that's ==, repr
will return such an expression e.g.
>>> print repr('hi') 'hi' # notice the quotes here as opposed to... >>> print str('hi') hi
If returning an expression doesn't make sense for an object, repr
should return a string that's surrounded by < and > symbols e.g. <blah>
.
To answer your original question:
In addition:
You can control the way an instance of your own classes convert to strings by implementing __str__
and __repr__
methods.
class Foo:
def __init__(self, foo):
self.foo = foo
def __eq__(self, other):
"""Implements ==."""
return self.foo == other.foo
def __repr__(self):
# if you eval the return value of this function,
# you'll get another Foo instance that's == to self
return "Foo(%r)" % self.foo
这篇关于%r 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!