slieep 发表于 2020-4-8 22:26:21

零基础“闭包”拓展阅读可以使用全局变量吗?和范本有什么区别?

本帖最后由 slieep 于 2020-4-8 22:28 编辑

python零基础的闭包拓展阅读中,小甲鱼设置程序将游戏中角色的移动位置保护起来,用的是闭包。我好奇不用内嵌函数,在局外先定义pos_x和pos_y,和小甲鱼的范本有什么区别?
求大佬解答!

这是小甲鱼的:
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 * step
      new_y = pos_y + direction * step
      # 检查移动后是否超出x轴边界
      if new_x < legal_x:
            pos_x = legal_x - (new_x - legal_x)
      elif new_x > legal_x:
            pos_x = legal_x - (new_x - legal_x)
      else:            
            pos_x = new_x
      # 检查移动后是否超出y轴边界
      if new_y < legal_y:
            pos_y = legal_y - (new_y - legal_y)
      elif new_y > legal_y:
            pos_y = legal_y - (new_y - legal_y)
      else:            
            pos_y = new_y
      return pos_x, pos_y
    return moving
   
move = create()
print('向右移动10步后,位置是:', move(, 10))
print('向上移动130步后,位置是:', move(, 130))
print('向左移动10步后,位置是:', move([-1, 0], 10))
这是我稍作修改的:origin = (0, 0)         # 原点
legal_x = [-100, 100]   # x轴的移动范围
legal_y = [-100, 100]   # y轴的移动范围

pos_x=0
pos_y=0
# 原点位置   
def moving(direction, step):
# direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动
# step参数设置移动的距离
    global pos_x, pos_y
    new_x = pos_x + direction * step
    new_y = pos_y + direction * step
    # 检查移动后是否超出x轴边界
    if new_x < legal_x:
      pos_x = legal_x - (new_x - legal_x)
    elif new_x > legal_x:
      pos_x = legal_x - (new_x - legal_x)
    else:            
      pos_x = new_x
    # 检查移动后是否超出y轴边界
    if new_y < legal_y:
      pos_y = legal_y - (new_y - legal_y)
    elif new_y > legal_y:
      pos_y = legal_y - (new_y - legal_y)
    else:            
      pos_y = new_y
    return pos_x, pos_y
   

print('向右移动10步后,位置是:', moving(, 10))
print('向上移动130步后,位置是:', moving(, 130))
print('向左移动10步后,位置是:', moving([-1, 0], 10))




zltzlt 发表于 2020-4-9 08:05:08

不建议在函数中修改全局变量

slieep 发表于 2020-4-9 19:19:15

我似乎明白了!
用闭包的话,可以通过del move,初始化角色位置到(0,0)。
但如果用全局变量,没法初始化角色位置。
这样理解应该没错?
页: [1]
查看完整版本: 零基础“闭包”拓展阅读可以使用全局变量吗?和范本有什么区别?