在 Python IDLE 中,“打印"变量和仅写入变量有什么区别? [英] In Python IDLE, what's the difference between 'print'ing a variable and just writing the variable?

查看:84
本文介绍了在 Python IDLE 中,“打印"变量和仅写入变量有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 IDLE 解释器中,我使用 dpkt 执行以下操作:

At the IDLE interpreter I do the following with dpkt:

for ts, buf in pcap:
  eth = dpkt.ethernet.Ethernet(buf)

现在,当我尝试查看 'eth' 的内容时,我可以打印它,或者只写变量名.

Now, when I try to see the contents of 'eth' I can either print it, or just write the variable name.

当我这样做时:

print eth

我明白了:

O&áÿE(r @,òÀ¨
DYP?Jò}PªpÉ

然而,当我简单地写:

eth

我得到了更多的预期输出:

I get the more expected output of:

Ethernet(src='<removed>', dst='<removed>', data=IP(src='<removed>', off=16384, dst='<removed>', sum=11506, len=40, p=6, ttl=128, id=29344, data=TCP(seq=2527752393, ack=218580057, win=16202, sum=62077, flags=16, dport=80, sport=51626)))

所以我的问题是,做打印(变量)"和只写变量名之间的根本区别是什么?如果我做一个简单的分配(即x = 100"),print x"和x"都会得到100"的结果

So my question is, what's the fundamental difference between doing a "print (variable)" and just writing the variable name? If I do a simple assignment (ie. "x = 100") I'll get a result of "100" for both "print x" and "x"

推荐答案

print(variable) 等于 print(str(variable))

variable 等于 print(repr(variable))

我的猜测是 dpkt.ethernet.Ethernet 类的 __repr____str__ 方法产生了这些完全不同的结果.

My guess is that the __repr__ and __str__ method of the class dpkt.ethernet.Ethernet produce these completely different results.

更新:看看源代码告诉我我是对的.

这篇关于在 Python IDLE 中,“打印"变量和仅写入变量有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆