0

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 ~

2
  • The n comes from you. And you haven't shown that part yet. What do you do with test now that you have it? Commented Sep 10, 2022 at 16:43
  • Does this answer your question? Understanding Nested functions in python Commented Sep 10, 2022 at 17:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Halo John thankyou for your answer :) i really appreciate it. so, how can i call stacimethod from return the function? i tried to call function like this -> halo = partition_by_mod(8) print(halo.(80)) and i got the result "invalid syntax"
@DennySugianto, partition_by_mod() calls staticmethod() itself (note the parenthesized argument list after its name) and returns the return value of that call. There's no particular reason to think that the return value provides a way to call staticmethod() again, and my best guess would be that you don't, in fact, actually want to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.