How do nested functions work in Python?

后端 未结 9 503
春和景丽
春和景丽 2020-12-01 04:50
def maker(n):
    def action(x):
        return x ** n
    return action

f = maker(2)
print(f)
print(f(3))
print(f(4))

g = maker(3)
print(g(3))

print(f(3)) # stil         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 05:31

    You can see it as all the variables originating in the parent function being replaced by their actual value inside the child function. This way, there is no need to keep track of the scope of the parent function to make the child function run correctly.

    See it as "dynamically creating a function".

    def maker(n):
      def action(x):
        return x ** n
      return action
    
    f = maker(2)
    --> def action(x):
    -->   return x ** 2
    

    This is basic behavior in python, it does the same with multiple assignments.

    a = 1
    b = 2
    a, b = b, a
    

    Python reads this as

    a, b = 2, 1
    

    It basically inserts the values before doing anything with them.

提交回复
热议问题