打印到标准输出时的python输出与存储在字典中的输出不同 [英] python output different when printed to std out than stored in dict
问题描述
我正在尝试使用 dnspython
进行区域传输,然后将 A 记录存储到我可以稍后从中弹出值的字典中.见下图:
导入 dns.zone导入 dns.query从 dns.exception 导入 DNSException从 dns.rdataclass 导入 *从 dns.rdatatype 导入 *域 = "mydomain.com"ns = '1.2.3.4'尝试:zone = dns.zone.from_xfr(dns.query.xfr(ns, domain))打印区域原点:",zone.origin除了 DNSException,e:打印 e.__class__, e对于 zone.iterate_rdatas('A') 中的 (name, ttl, rdata):记录 = { 名称:rdata }打印名称,rdata打印记录
为什么当我使用 print
时的输出与我在字典中存储相同的变量 name, rdata
并打印该 dict 时的输出不同?见下面的输出:
www 1.1.1.1{<DNS 名称 www>:<DNS IN A rdata:1.1.1.1>}
我想澄清我的问题:我如何使字典看起来像:{ 'www' : '1.1.1.1' }
发生这种情况是因为 dict 的内容是通过在其每个键/值上调用 repr
来表示的,而打印一个对象直接会调用str
.
示例:
<预><代码>>>>弗雷德班级:... def __repr__(self):...返回repr 返回的值"... def __str__(self):...返回str返回的值"...>>>d = {1:弗雷德()}>>>打印{1:repr 返回的值}>>>打印 d[1]str 返回的值对此您无能为力……您可以编写自己的类版本并定义__repr__
,使其与__str__ 的行为相同代码>.或者您可以编写一个自定义的 dict 打印函数来呈现
__str__
而不是 __repr__
的结果.但是没有内置的方法可以强制 print somedict
使用 __str__
而不是 __repr__
.
I'm trying to do a zonetransfer with dnspython
, and then store the A record's into a dictionary that i can pop values from later. See below:
import dns.zone
import dns.query
from dns.exception import DNSException
from dns.rdataclass import *
from dns.rdatatype import *
domain = "mydomain.com"
ns = '1.2.3.4'
try:
zone = dns.zone.from_xfr(dns.query.xfr(ns, domain))
print "Zone origin:", zone.origin
except DNSException, e:
print e.__class__, e
for (name, ttl, rdata) in zone.iterate_rdatas('A'):
record = { name : rdata }
print name, rdata
print record
why is the output when i use print
is different than when i store the same variables name, rdata
in a dictionary, and print that dict? See output below:
www 1.1.1.1
{<DNS name www>: <DNS IN A rdata: 1.1.1.1>}
I guess to clarify my question: How do I make the dict look like :
{ 'www' : '1.1.1.1' }
This is happening because the contents of a dict are represented by calling repr
on each of its keys/values, whereas printing an object directly will call str
.
Example:
>>> class Fred:
... def __repr__(self):
... return "value returned by repr"
... def __str__(self):
... return "value returned by str"
...
>>> d = {1: Fred()}
>>> print d
{1: value returned by repr}
>>> print d[1]
value returned by str
There's not a whole lot you can do about this... You could write your own version of the classes you're trying to print and define __repr__
so it behaves identically to __str__
. Or you could write a custom dict-printing function that renders the result of __str__
instead of __repr__
. But there's no built-in way to force print somedict
to use __str__
instead of __repr__
.
>>> print "{" + ", ".join("{} : {}".format(repr(str(key)), repr(str(value))) for key, value in d.iteritems()) + "}"
{'1' : 'value returned by str'}
这篇关于打印到标准输出时的python输出与存储在字典中的输出不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!