Analyze the difference between python calling function with parentheses and without parentheses

  • 2021-12-11 18:09:12
  • OfStack

Let's look at the difference between python calling function with parentheses and without parentheses. The specific code is as follows;


 def  bracket(data):
  
      return data
 
  if __name__ == '__main__':
  
      #  The result of the call without parentheses: <function bracket at 0x0000000004DD0B38>,a Is the whole function body, is 1 You don't have to wait for the function to finish executing 
 
     a = bracket
 
     print a
 
     #  The result of the call in parentheses: 6 ,b Is the value returned after the function is executed 6, You must wait for the result of the completion of the function 
 
     b = bracket(6)
 
    print b

1. Without parentheses, the function itself, the whole function body and a function object are called, without waiting for the execution of the function to be completed.

2. With parentheses (parameters or no parameters), what is called is the execution result of the function, and the result of the completion of the execution of the function must be waited for.

To put it simply:

If parentheses are used, only if and functions are called. hello() Call function; hello Is just a name bound to a function that can be used to pass a 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 Returns a different value because the id Receives 1 completely independent object as its parameter for each call of. Use id(hello) , id Gets the function object itself. Use id(hello()) , id Will be obtained by calling the hello The returned object;


Related articles: