I am new to python. I want to know the difference between the statements:
print(hello())
print(hello()())
Why the first statement returns the type & memory address and the second statement returns the data after the logic is evaluated?
def hello(name='Jose'):
def greet():
return '\t This is inside the greet() function'
def welcome():
return "\t This is inside the welcome() function"
if name == 'Jose':
return greet
else:
return welcome
result = hello()
print(hello()) # Returns <function hello.<locals>.greet at 0x00000241AD3E5040>
print(result()) # Returns This is inside the greet() function
print(hello()()) # Returns This is inside the greet() function
CodePudding user response:
The function hello returns another function.You call the returned function using (). Maybe if you split it it becomes more obvious
func = hello()
func()
CodePudding user response:
Functions are first class citizens in python. They act as any other data type. The hello function returns a function. When you are doing hello(), it is returning a function so you could do something like this:
def hello(name="Jose"):
...
greet = hello() # Returns the greet function
print(greet()) # Returns '\t This is inside the greet() function'
By doing hello()() you are calling the function that is returned by the hello function. For more reading on first class citizen functions in python, look here.
CodePudding user response:
This pattern is a "closure'.
When you run hello() it returns a function. so result = hello() sets the variable result to be a function.
try:
def hello(name='Jose'):
def greet():
return '\t This is inside the greet() function'
def welcome():
return "\t This is inside the welcome() function"
if name == 'Jose':
return greet
else:
return welcome
result = hello()
print(callable(result))
So just like was can now do result() we can also skip defining result and do hello()() as we know, hello() returns a function and we then immediately call it.
