python 2.7中print和print()的区别是什么

Tai*_*lla 10 python python-2.7

我是Python的新手.

我在python 2.7上运行以下代码,当我使用print或print()时,我看到不同的结果.这两个功能有什么区别?我读了其他问题,例如,这个问题,但我找不到答案.

class Rectangle:
    def __init__(self, w, h):
        self.width = w
        self.height = h
    def __str__(self):
        return "(The width is: {0}, and the height is: {1})".format(self.width, self.height)

box = Rectangle(100, 200)
print ("box: ", box)
print "box: ", box
Run Code Online (Sandbox Code Playgroud)

结果是:

('box: ', <__main__.Rectangle instance at 0x0293BDC8>)
box:  (The width is: 100, and the height is: 200)
Run Code Online (Sandbox Code Playgroud)

Rem*_*ich 14

在Python 2.7(以及之前)中,print是一个带有许多参数的语句.它打印参数,中间有空格.

所以,如果你这样做

print "box:", box
Run Code Online (Sandbox Code Playgroud)

它首先打印字符串"box:",然后box打印一个空格,然后打印任何打印(其__str__功能的结果).

如果你这样做

print ("box:", box)
Run Code Online (Sandbox Code Playgroud)

你给了一个参数,一个由两个元素组成的元组("box:"和对象box).

元组打印作为它们的表示(主要用于调试),因此它调用__repr__其元素而不是它们__str__(它应该提供用户友好的消息).

这就是你看到的差异:(The width is: 100, and the height is: 200)是你的盒子的结果__str__,但是<__main__.Rectangle instance at 0x0293BDC8>它的结果__repr__.

在Python 3及更高版本中,print()是任何其他函数的正常函数(因此print(2, 3)打印"2 3"并且print 2, 3是语法错误).如果你想在Python 2.7中拥有它,那就放

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

在源文件的顶部,使其稍微为现在做好准备.