当您使用另一个函数作为 print() 函数的参数时会发生什么?

What happens when you use another function as the argument for the print() function?

我是初学者,所以我不太了解 print() 函数背后的底层过程,但我很好奇这样的事情背后的过程:

def test():
    print("hi")
    return "hi"

print(test())

这会输出来自 test() 函数内的 print() 的“hi”消息以及来自 return 语句的“hi”消息。本能地,我只会期望 return 语句中的“hi”。

任何人都可以简单地解释一下为什么我们会得到两者吗?我希望它是这样的: 当使用诸如 test() 之类的函数输出作为 print 函数的参数时,首先调用 test() 函数(因此产生第一个“hi”),然后打印其 return 输出(产生第二个“嗨”)。

我在这里在某种程度上是正确的吗?如果能阐明这里发生的事情并提高我的理解,我将不胜感激:)

很简单

print(test())

等同于

result = test()
print(result)

第一行调用 test 函数(在其主体中打印 'hi')并将名称 result 分配给 return 值,巧合的是还有 'hi'.

第二行打印由 test 编辑的值 return。