浅谈闭包
闭包 = 函数 + 环境变量
def factory(): pos = 0 def go(step): nonlocal pos new_pos = pos + step pos = new_pos return pos return go tourist = factory() print(tourist(2)) print(tourist.__closure__) # 打印闭包的环境变量 print(tourist(3)) print(f'环境变量pos的值为{tourist.__closure__[0].cell_contents}') print(tourist(5))
输出:
2 (<cell at 0x000001D819D00C78: int object at 0x00007FFA1FE1B370>,) 5 环境变量pos的值为5 10
闭包不会操作全局变量,环境变量常驻内存,要小心使用;该类型的问题可以用面向对象实现,用类变量代替环境变量