How A Function In Python Is Getting Called By Just Typing The Name Of Function And Not Using Brackets
Solution 1:
I don't think you understand decorators. Let's make a minimal example.
defmy_decorator(some_function):
defnew_function(*args, **kwargs):
'announces the result of some_function, returns None'
result = some_function(*args, **kwargs)
print('{} produced {}'.format(some_function.__name__, result))
return new_function # NO FUNCTION CALL HERE!@my_decoratordefmy_function(a, b):
return a + b
my_function(1, 2) # will print "my_function produced 3"We have a simple function my_function which returns the sum of its two arguments and a decorator which will just print out the result of whatever function it decorates.
Note that
@my_decoratordefmy_function(a, b):
return a + b
is equivalent to
def my_function(a, b):
return a + b
my_function = my_decorator(my_function)
Since my_decorator accepts a function as an argument (here we are giving it my_function) and returns a new functionnew_function (without calling it!), we effectively override my_function because we reassign the name to whatever my_decorator returns.
In action:
>>>my_function(1, 2)
my_function produced 3
Note that at every point in the example when a function is called, it happens with the parentheses-syntax. Here are all the function calls that happen in the first block of code I posted, in order:
my_decorator(my_function)is called and the return value is reassigned to the namemy_function. This either happens through the@syntax or more explicitly in the equivalent code snippet.my_function(1, 2)is called. At this point,my_functionis thenew_functionthat got returned by the decorator. Brain-parse it asnew_function(1, 2).- Inside the body of
new_function, the argument we gave tomy_decoratoris called (result = some_function(*args, **kwargs)) which happens to be the value ofmy_functionbefore the reassignment that happened in step 1. printis called.
If you want to understand how new_function is holding on to some_function despite my_decorator already having returned from its call, I suggest looking into the topics free variables and closures.
Solution 2:
return hcf does not call the function because there are no parentheses, as you noticed. The decor function is used as a decorator which reassigns the name lcm to refer to the returned function. What I mean by this is that
@decordeflcm(a, b):
// ...
is equivalent to
def lcm(a, b):
// ...
lcm = decor(lcm)
After this executes, lcm refers to the function hcf. So calling lcm(2, 4) now executes the code in hcf. I think the key here is to understand that at the line lcm(2, 4), lcm and hcf are two names which refer to the same function.
Post a Comment for "How A Function In Python Is Getting Called By Just Typing The Name Of Function And Not Using Brackets"