How do nested functions work in Python?

后端 未结 9 495
春和景丽
春和景丽 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:46

    Because at the time when you create the function, n was 2, so your function is:

    def action(x):
        return x ** 2
    

    When you call f(3), x is set to 3, so your function will return 3 ** 2

提交回复
热议问题