Is there an overhead when nesting functions in Python?

前端 未结 6 1806
终归单人心
终归单人心 2020-12-04 23:28

In Python, if I have a child function within a parent function, is the child function \"initialised\" (created) every time the parent function is called? Is there any overhe

6条回答
  •  不思量自难忘°
    2020-12-05 00:07

    Yes. This enables closures, as well as function factories.

    A closure causes the inner function to remember the state of its environment when called.

    def generate_power(number):
    
        # Define the inner function ...
        def nth_power(power):
            return number ** power
    
        return nth_power
    

    Example

    >>> raise_two = generate_power(2)
    >>> raise_three = generate_power(3)
    
    >>> print(raise_two(3))
    8
    >>> print(raise_three(5))
    243
    """
    

提交回复
热议问题