Python 术语 - 额外的 REPL 输出叫什么?
Python terminology- what are the extra REPL outputs called?
考虑以下代码:
class Greet:
def __init__(self, greeting='Hello'):
print(greeting)
if __name__ == '__main__':
print('Initializing and assigning')
greet = Greet('Shalom!')
print('Only initializing a class')
Greet()
如果我 运行 脚本,我得到输出:
Initializing and assigning
Shalom!
Only initializing a class
Hello
但是,假设我在交互式 REPL 中 运行ning 上面的代码,交互如下:
In 1> greet = Greet('Shalom!')
Shalom!
In 2> Greet()
Hello
<__main__.Greet object at 0x7fac80cc84c0>
如果您注意到,在第二个输入中,即 Greet()
,我得到第二行,我相信这是导致 评估[=25 的对象的 repr
=] 输入。这个 EXTRA 输出叫什么?因为在我看来,这是 REPL 本身的一个怪癖。
从上面的评论中复制实际答案:
In the interactive shell, any expressions (not assignments) evaluating
to a non-None
value will be printed. This does not happen in
scripts. You are seeing this output in addition to the actual print
statements. If you had put instead greet2 = Greet()
then you
wouldn't have seen this.
但是发布此答案是为了发表不符合评论格式的附加评论...您可能在任何情况下都不希望让您的对象执行 操作 关于初始化——最好把它放到一个单独的方法中:
>>> class Greeter:
... def __init__(self, greeting='Hello'):
... self.greeting = greeting
... def greet(self):
... print(self.greeting)
...
>>> greeter = Greeter()
>>> greeter.greet()
Hello
在任何情况下您都不会在此处看到任何附加行,因为 greet
方法 returns None
.
考虑以下代码:
class Greet:
def __init__(self, greeting='Hello'):
print(greeting)
if __name__ == '__main__':
print('Initializing and assigning')
greet = Greet('Shalom!')
print('Only initializing a class')
Greet()
如果我 运行 脚本,我得到输出:
Initializing and assigning
Shalom!
Only initializing a class
Hello
但是,假设我在交互式 REPL 中 运行ning 上面的代码,交互如下:
In 1> greet = Greet('Shalom!')
Shalom!
In 2> Greet()
Hello
<__main__.Greet object at 0x7fac80cc84c0>
如果您注意到,在第二个输入中,即 Greet()
,我得到第二行,我相信这是导致 评估[=25 的对象的 repr
=] 输入。这个 EXTRA 输出叫什么?因为在我看来,这是 REPL 本身的一个怪癖。
从上面的评论中复制实际答案:
In the interactive shell, any expressions (not assignments) evaluating to a non-
None
value will be printed. This does not happen in scripts. You are seeing this output in addition to the actual print statements. If you had put insteadgreet2 = Greet()
then you wouldn't have seen this.
但是发布此答案是为了发表不符合评论格式的附加评论...您可能在任何情况下都不希望让您的对象执行 操作 关于初始化——最好把它放到一个单独的方法中:
>>> class Greeter:
... def __init__(self, greeting='Hello'):
... self.greeting = greeting
... def greet(self):
... print(self.greeting)
...
>>> greeter = Greeter()
>>> greeter.greet()
Hello
在任何情况下您都不会在此处看到任何附加行,因为 greet
方法 returns None
.