python-3.x - 访问已删除然后重新创建的全局变量
问题描述
如果我们删除函数中的全局变量并在函数中重新创建相同的变量,这样我们就无法在函数之外访问它,但删除后仍然可以访问它怎么办?
代码:
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
解决方案
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
推荐阅读
- node.js - 使用 swagger-ui-express 和 swagger-jsdoc 时如何在 swagger 文件中正确使用 $ref
- c++ - ComputeLibrary 数据类型模板
- docker - 当我将 go 与 docker compose 一起使用时出现“没有 Go 文件...”错误
- ios - 使用相同的默认 UIImage 对象进行单元重用/初始化
- angular-material - 如何启用具有多选和动态列的 mat-table
- firebase - Google Cloud Functions 的开发环境
- json - Flutter:如何解码这个复杂的 JSON 字符串
- python - 如何在 python-jsonschema 文档中设置本地文件引用?
- android - 挣扎着手势拖动
- docker - 无法在无人机 docker build 上标记图像:解析参考时出错:“:最新”不是有效的存储库/标签:参考格式无效