可变的默认参数
def append_to(element, to=[]):
to.append(element)
return to
my_list = append_to(12)
print(my_list)
my_other_list = append_to(42)
print(my_other_list)
# [12]
# [12, 42]
for 循环i 的数值+闭包的延迟绑定
def create_multipliers():
return [lambda x : i * x for i in range(5)]
for multiplier in create_multipliers():
print multiplier(2)
# 8
# 8
# 8
# 8
# 8
def create_multipliers():
return [lambda x, i=i: i * x for i in range(5)]
for multiplier in create_multipliers():
print(multiplier(2))
#0
#2
#4
#6
#8