首页 > 解决方案 > 访问已删除然后重新创建的全局变量

问题描述

如果我们删除函数中的全局变量并在函数中重新创建相同的变量,这样我们就无法在函数之外访问它,但删除后仍然可以访问它怎么办?

代码:

f=100
print(f)

def change():
    global f
    print(f)
    f=200
    print(f)
    del f #deleted
    #print(f) we get error for this line
    f=500# again created as local variable
    g=5000# this is also local means can't access outside the function
    print(f)

change()
print(f)#We delete f but how it exist.although it is local var of change function
print(g)#Here we get error that  g is not defined

标签: python-3.x

解决方案


f被宣布为全球性的;当您重新创建它时,它会在全局范围内重新创建。
g另一方面是本地的,不能在其范围之外访问。

def change():
    global f      # f is global 
    del f         # deleted
    f = 500       # recreated as GLOBAL variable
    g = 5000      # this is LOCAL ==>> can't access outside the scope

change()
print(f)  # f was deleted, then recreated in the global scope
print(g)  # raises NameError: name 'g' is not defined

推荐阅读