|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
链接如下:https://fishc.com.cn/thread-42656-1-1.html
程序如下:origin = (0, 0) # 原点
legal_x = [-100, 100] # x轴的移动范围
legal_y = [-100, 100] # y轴的移动范围
def create(pos_x=0, pos_y=0):
# 初始化位于原点为主
def moving(direction, step):
# direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动
# step参数设置移动的距离
nonlocal pos_x, pos_y
new_x = pos_x + direction[0] * step
new_y = pos_y + direction[1] * step
# 检查移动后是否超出x轴边界
if new_x < legal_x[0]:
pos_x = legal_x[0] - (new_x - legal_x[0])
elif new_x > legal_x[1]:
pos_x = legal_x[1] - (new_x - legal_x[1])
else:
pos_x = new_x
# 检查移动后是否超出y轴边界
if new_y < legal_y[0]:
pos_y = legal_y[0] - (new_y - legal_y[0])
elif new_y > legal_y[1]:
pos_y = legal_y[1] - (new_y - legal_y[1])
else:
pos_y = new_y
return pos_x, pos_y
return moving
move = create()
print('向右移动10步后,位置是:', move([1, 0], 10))
print('向上移动130步后,位置是:', move([0, 1], 130))
print('向左移动10步后,位置是:', move([-1, 0], 10))
问题如下:1.闭包的内嵌函数一定要return回自身吗?如程序中的return moving
2.如果我屏蔽 move =create()直接 print('向右移动10步后,位置是:', create([1, 0], 10)) ,为什么会返回输出一个迭代器 ”向右移动10步后,位置是: <function create.<locals>.moving at 0x02C52B28>”,关于输出迭代器我一直没搞懂为什么会输出迭代器?
3.小甲鱼在程序后有一段注解 ”move = create(),如果当 move 变量重新被赋值的话,相应的 pos_x 和 pos_y 也都会被初始化为 0”。为什么我感觉pos_x 和 pos_y 没有被初始化为0?因为运行上面的程序得到的是:向右移动10步后,位置是: (10, 0)
向上移动130步后,位置是: (10, 70)
向左移动10步后,位置是: (0, 70) 。如果初始化为0了,应该是:(10, 0)
(0, 70)
(-10,0)
1. 是的。
2. 这不是迭代器,因为你没有调用 moving,所以它就返回 moving 函数自身。你可以这样改:
- print('向右移动10步后,位置是:', create()([1, 0], 10))
复制代码
3. 注意是 当 move 变量重新被赋值,move 变量一直是原来的,pos_x 和 pos_y 当然不会初始化了。这样改 pos_x 和 pos_y 才会初始化:
- legal_x = [-100, 100] # x轴的移动范围
- legal_y = [-100, 100] # y轴的移动范围
- def create(pos_x=0, pos_y=0):
- # 初始化位于原点为主
- def moving(direction, step):
- # direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动
- # step参数设置移动的距离
- nonlocal pos_x, pos_y
- new_x = pos_x + direction[0] * step
- new_y = pos_y + direction[1] * step
- # 检查移动后是否超出x轴边界
- if new_x < legal_x[0]:
- pos_x = legal_x[0] - (new_x - legal_x[0])
- elif new_x > legal_x[1]:
- pos_x = legal_x[1] - (new_x - legal_x[1])
- else:
- pos_x = new_x
- # 检查移动后是否超出y轴边界
- if new_y < legal_y[0]:
- pos_y = legal_y[0] - (new_y - legal_y[0])
- elif new_y > legal_y[1]:
- pos_y = legal_y[1] - (new_y - legal_y[1])
- else:
- pos_y = new_y
- return pos_x, pos_y
- return moving
- move = create()
- print('向右移动10步后,位置是:', move([1, 0], 10))
- move = create()
- print('向上移动130步后,位置是:', move([0, 1], 130))
- move = create()
- print('向左移动10步后,位置是:', move([-1, 0], 10))
复制代码
|
|