Reputation: 9
I wanna know, what is main idea function inside a function in djanggo?, something like this example.
def partition_by_mod(base):
def func(n):
return n % base
return staticmethod(func)
when I call this function like this test = partition_by_mod(8), so I'm wondering where the "n" comes from.
thank you ~
Upvotes: 0
Views: 54
Reputation: 180266
what is main idea function inside a function in djanggo?
It's the same as a function defined anywhere else, but it is accessible by name only within the outer function, and it closes over the variables (such as base
) of the scope in which it is defined, so that they are indirectly accessible to whomever calls the function. Your particular example could be replaced by a lambda:
def partition_by_mod(base):
return staticmethod(lambda n: n % base)
when I call this function like this test = partition_by_mod(8), so I'm wondering where the "n" comes from.
The argument is provided by the code that actually calls the function. Note in particular that
staticmethod(func)
does not call func
, but rather passes func
itself as an argument, presumably with the idea that staticmethod
will call it. This is sometimes described as a "callback function". You can recognize a function call by the parenthesized argument list, which is required even when there are zero arguments. If and when staticmethod
does call it, staticmethod
has the responsibility to provide the needed argument.
Upvotes: 1