说明:

  • 在python的循环中,可能会存在使用到上一次循环的值
  • 在进入下次循环之前,最好清理一下上一次的变量,便于调试

查看变量方式:

## 方式1(查看局部变量):
dir()
# 输出:
['In',
 'Out',
 '_',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 'exit',
 'get_ipython',
 'quit']
## 方式2(查看全局变量):
### 注:globals是字典
list(globals())
# 输出:
['__name__',
 '__doc__',
 '__package__',
 '__loader__',
 '__spec__',
 '__builtin__',
 '__builtins__',
 '_ih',
 '_oh',
 '_dh',
 'In',
 'Out',
 'get_ipython',
 'exit',
 'quit',
 '_',
 '__',
 '___',
 '_i',
 '_ii',
 '_iii',
 '_i1',
 '_1',
 '_i2']
# 更多关于dir、globals等说明,参考链接:https://blog.csdn.net/weixin_38682750/article/details/80365025?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight
# 可以看到,在全局范围内,两者的变量数量相等
len(dir()), len(globals())
(26, 26)
# 但是在函数内,两者数量就不相等了
def c():
    a = 1
    print(f'局部变量数量:{len(dir())}, 全局变量数量:{len(globals())}')
c()
局部变量数量:1, 全局变量数量:29
def clear_variable():
    for key in list(globals()):
        if key not in system_variable:
            globals().pop(key)  # 删除局部变量

# 在进入循环前,把定义的变量备份
system_variable = dir()
# 添加自身
system_variable.append('system_variable')

a = 1
b = 2
print(f'循环之前的a,b:{(a, b)}')

clear_variable()  # 清理变量
try:
    print(a, b)
except:
    print('a,b已被清理')

print('\n进入循环...')
system_variable.append('i')  # 将循环所需变量也加入
for i in range(5):
    clear_variable()  # 清理变量
    try:
        print(a, b)
    except:
        print(f'循环{i}内a,b已被清理')
    # 再次定义变量
    a = i
    b = i * 2
    print(f'循环内的a,b:{a, b}\n')
# 输出:
循环之前的a,b:(1, 2)
a,b已被清理

进入循环...
循环0内a,b已被清理
循环内的a,b:(0, 0)

循环1内a,b已被清理
循环内的a,b:(1, 2)

循环2内a,b已被清理
循环内的a,b:(2, 4)

循环3内a,b已被清理
循环内的a,b:(3, 6)

循环4内a,b已被清理
循环内的a,b:(4, 8)
posted on 2020-07-02 18:24  jaysonteng  阅读(1950)  评论(0编辑  收藏  举报