In Python IDLE, what's the difference between 'print'ing a variable and just writing the variable?

前端 未结 2 1549
傲寒
傲寒 2020-12-12 01:21

At the IDLE interpreter I do the following with dpkt:

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

Now, when I try to see the c

相关标签:
2条回答
  • 2020-12-12 01:50

    There are two functions for representing data as a string in python: repr() and str().

    When you use a print statement, the str function is called on whatever arguments you supplied for the print statement (and a newline is appended to the end of the result). For example, x = 100; print x will call str(x). The result ("100") will have a newline appended to it, and it will be sent to stdout.

    When you execute something other than a print statement, the interpreter will print whatever value the expression yields using repr, unless the value is None, in which case nothing is printed.

    In most cases, there are only subtle differences between the two. Objects, however, often define their own non-identical __str__ and __repr__ methods (which define the behavior for the str and repr built-in functions for that object). In your example, the eth object's __repr__ method must be different from the __str__ method.

    I would speculate that the __str__ method is returning a binary string representation of the object to send across a network, but I can't be sure.

    0 讨论(0)
  • 2020-12-12 02:07

    print(variable) equals to print(str(variable))

    whereas

    variable equals to print(repr(variable))

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

    Update: Having a look at the source code tells me I am right.

    0 讨论(0)
提交回复
热议问题