之间有什么区别__str__和__repr__在__str__?
当您object.__repr__()在Python中调用该方法时,您会得到类似这样的内容:
Run Code Online (Sandbox Code Playgroud)<__main__.Test object at 0x2aba1c0cf890>
如果你超载__repr__(),有没有办法得到一个内存地址,除了调用super(Class, obj).__repr__()和重新出现之外?
repr():对象的可评估字符串表示形式(可以"eval()"它,这意味着它是一个求值为Python对象的字符串表示形式)
换一种说法:
>>> x = 'foo'
>>> repr(x)
"'foo'"
Run Code Online (Sandbox Code Playgroud)
问题:
repr(x)?(当我这样做时,我不会得到它们str(x))'foo'在做的时候会得到eval("'foo'")而不是x那个对象?最近,我有很多的麻烦__repr__(),format()和编码. 输出__repr__()应该编码还是unicode字符串?__repr__()Python中 的结果是否有最佳编码?我想输出的内容确实有非ASCII字符.
我使用Python 2.x,并希望编写可以轻松适应Python 3的代码.程序因此使用
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function # The 'Hello' literal represents a Unicode object
Run Code Online (Sandbox Code Playgroud)
以下是一些困扰我的其他问题,我正在寻找解决它们的解决方案:
sys.stdout.encoding设置了UTF-8,但最好是其他情况也能正常工作).sys.stdout.encoding是None).__repr__()功能的代码目前有很多return ….encode('utf-8'),而且很重要.有什么强劲和轻松的吗?return ('<{}>'.format(repr(x).decode('utf-8'))).encode('utf-8'),即对象的表示被解码,放入格式化字符串,然后重新编码.我想避免这种错综复杂的转变.为了编写__repr__()与这些编码问题相关的简单函数,您建议做什么?
当我创建一个包含反斜杠的字符串时,它们会重复:
>>> my_string = "why\does\it\happen?"
>>> my_string
'why\\does\\it\\happen?'
Run Code Online (Sandbox Code Playgroud)
为什么?
python 2.7.5 str()和repr()函数有什么区别?
python.org上的说明:
该
str()函数用于返回值相当于人类可读的值的表示,同时repr()用于生成可由解释器读取的表示(或者SyntaxError如果没有等效语法则强制执行)
但这对我来说并不清楚.
一些例子:
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'" # repr is giving an extra double quotes
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285' # repr is giving value with more precision
Run Code Online (Sandbox Code Playgroud)
所以我想知道以下内容
str()应该何时使用,何时使用repr()?str()做哪些repr()不可以?repr()做哪些str()不可以?有没有像Python的repr一样工作的Java方法?例如,假设该函数名为repr,
"foo\n\tbar".repr()
Run Code Online (Sandbox Code Playgroud)
会回来的
"foo\n\tbar"
不
foo
bar
至于toString.
我编写了一个函数来创建VALUESSQL查询的一部分:
def query_values(data_iterator):
return ',\n'.join('\n({})\n'.format(',\n'.join('"{}"'.format(value) for value in data_row)
) for data_row in data_iterator
),
Run Code Online (Sandbox Code Playgroud)
当我调用此函数和print结果时,得到的是:
query_values:
('\n("801",\n"printer",\n"barcode printer")\n,\n\n("844",\n"laptop",\n"windows")\n,\n\n("997",\n"printer",\n"barcode printer")\n',)
Run Code Online (Sandbox Code Playgroud)
合而为一。而不是换行,\n而是显示。
本来我有一个\n,但是后来我插入了多个,只是看它们是否会显示出来。
第二个问题是整个内容中都有括号,这是我不想要的。
我对这两个问题感到困惑,我想出了第二个问题的解决方案:
函数结尾处有一个逗号。逗号导致函数返回一个元组,而不是单个字符串。
我删除了逗号:
def query_values(data_iterator):
return ',\n'.join('\n({})\n'.format(',\n'.join('"{}"'.format(value) for value in data_row)
) for data_row in data_iterator
)
Run Code Online (Sandbox Code Playgroud)
并且解决了两个问题。现在的输出是:
query_values:
("801",
"printer",
"barcode printer")
,
("844",
"laptop",
"windows")
,
("997",
"printer",
"barcode printer")
Run Code Online (Sandbox Code Playgroud)
我把逗号放回去,并且\n显示了。我删除了逗号,并且再次有多行。
我删除了无关的东西\n,所以现在我得到了想要的:
query_values:
("801","printer","barcode printer"),
("844","laptop","windows"),
("997","printer","barcode printer")
Run Code Online (Sandbox Code Playgroud)
因此,我的代码可以正常工作,但是我\n对旧版本代码中显示的字符完全感到困惑。为什么会这样呢? …
!s(applystr())和!r(applyrepr())可用于在格式化之前转换值.Run Code Online (Sandbox Code Playgroud)>>> import math >>> print 'The value of PI is approximately {}.'.format(math.pi) The value of PI is approximately 3.14159265359. >>> print 'The value of PI is approximately {!r}.'.format(math.pi) The value of PI is approximately 3.141592653589793.
有趣的是,转换后的值是输出repr(),而不是str().
>>> str(math.pi)
'3.14159265359'
>>> repr(math.pi)
'3.141592653589793'
Run Code Online (Sandbox Code Playgroud)
那么"转换价值"在这里意味着什么呢?使它不那么人性化?
如果有人在python中编写一个类,并且未能指定自己的__repr__()方法,则为它们提供默认方法.但是,假设我们要编写一个与默认行为具有相同或相似行为的函数__repr__().但是,我们希望此函数具有默认__repr__()方法的行为,即使__repr__()该类的实际重载也是如此.也就是说,假设我们想要编写一个与默认行为具有相同行为的函数,__repr__()而不管是否有人重载了该__repr__()方法.我们怎么做?
class DemoClass:
def __init__(self):
self.var = 4
def __repr__(self):
return str(self.var)
def true_repr(x):
# [magic happens here]
s = "I'm not implemented yet"
return s
obj = DemoClass()
print(obj.__repr__())
print(true_repr(obj))
Run Code Online (Sandbox Code Playgroud)
print(obj.__repr__())打印4,但print(true_repr(obj))打印如下:
<__main__.DemoClass object at 0x0000000009F26588>
python ×10
repr ×10
string ×4
python-2.7 ×2
ascii ×1
backslash ×1
encoding ×1
escaping ×1
formatting ×1
java ×1
newline ×1
object ×1
python-3.x ×1
tuples ×1