2.4.2 名称空间
y = 3
def func():
y = 1
print("函数func:", y) # 输出:1
func()
print("函数外:", y) # 输出:3def polygon_factory(n):
# 返回一个正n边形函数polygon
def polygon(turtle, side):
return turtle.polygon(n, side) # 绑定了闭包polygon_factory中的名称n和局部名称空间中的turtle和side
# 翻译成人话即这里的n用的是polygon_factory的参数n,而turtle和side是局部变量
return polygon
pentagon = polygon_factory(5) # 五边形函数
octagon = polygon_factory(8) # 八边形函数
my_turtle = MyTurtle()
pentagon(my_turtle, 50) # 边长为50的五边形
octagon(my_turtle, 50) # 边长为50的八边形Last updated