Files
Python_CookBook_repo/7.函数/7.在匿名函数中绑定变量的值.py
2025-09-10 16:12:45 +08:00

31 lines
681 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
# lambda函数中的变量如果被赋值了是可以动态修改的只要在每次调用之前修改就能实现变化
x = 1
a = lambda y: x + y
print(a(10))
x = x + 9
print(a(10))
x = x + 10
print(a(10))
# 如果你希望和正常函数一样在定义的时候绑死变量的值,那么你需要这样做
b = lambda y, t=x: t + y
print(b(10))
x = x-1
print(b(10))
# 比如有个比较聪明的函数
func = [lambda x : x + n for n in range(5)]
for f in func:
print(f(0))
func2 = [lambda x, n=n: x + n for n in range(5)]
for f in func2:
print(f(0))