问题描述
我有一个问题.让我们假设我们有函数 hello().带括号和不带括号有什么区别?当我调用 hello() 时,它指的是一个值等于这个函数的对象.或者也许我错了?当我不带括号调用它时会发生什么?
I have a question. Lets assume that we have function hello(). What is the difference between calling it with parentheses and without? When I call hello() it is referring to an object with value equals this function. Or maybe am I wrong? What happens when I call it without parentheses?
不知道为什么
def hello():
pass
print(id(hello))
print(id(hello()))
返回不同的结果
4400606744
4398942536
推荐答案
简答:见 https://nedbatchelder.com/text/names.html 以更好地了解对象和用于指代对象的名称之间的区别.
Short answer: see https://nedbatchelder.com/text/names.html to get a better understanding of the difference between objects and the names used to refer to objects.
当且仅在使用括号时调用函数.hello()
调用函数;hello
只是一个绑定到函数的名称,例如,可以用来将函数对象作为参数传递给另一个函数.
A function is called if and only if you use parentheses. hello()
calls the function; hello
is simply a name bound to the function, and can be used, for example, to pass the function object as an argument to another function.
def caller(f):
f()
def hello():
print("hi")
def goodbye():
print("bye")
caller(hello) # Prints "hi"
caller(goodbye) # Prints "bye"
关于您的更新,id
返回不同的值,因为对 id
的每次调用都会接收一个完全独立的对象作为其参数.使用 id(hello)
,id
获取函数对象本身.使用id(hello())
,id
正在通过调用hello
获取返回的对象;和
Regarding your update, id
returns different values because each call to id
receives a completely separate object as its argument. With id(hello)
, id
gets the function object itself. With id(hello())
, id
is getting the object returned by the call to hello
; it's the same as
x = hello()
print(id(x))
这篇关于在python中带括号和不带括号的调用函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!