python - Python全局变量不适用于新文件的用户定义函数
问题描述
当我运行下面的python代码时,结果是0、5
#file name main1.py
def getZ(x,y):
global Z
Z=x*x+y*y
return Z
global X,Y,Z
X=1
Y=2
Z=0
print(Z)
getZ(X,Y);
print(Z)
但是当我运行下面的文件时
#file name main2.py
import getZ
global X,Y,Z
X=1
Y=2
Z=0
print(Z)
getZ.getZ(X,Y);
print(Z)
具有新的用户定义功能,
#file name getZ.py
def getZ(x,y):
global Z
Z=x*x+y*y
return Z
结果为 0, 0
我无法理解这种情况。
有人可以帮我吗?
感谢您的意见。
解决方案
Python 没有真正的全局变量,只有模块级全局变量。访问的是,Z
而不是你设置的。getZ
getZ.Z
__main__.Z
main2.py
这会起作用:
#file name main2.py
import getZ
X=1
Y=2
getZ.Z = 0 # Set the value of the variable `getZ.getZ` looks for.
print(getZ.Z)
getZ.getZ(X, Y)
print(getZ.Z)
推荐阅读
- scala - Spark 2.3:展平结构数组,并创建新列
- java - 在应用程序启动时出现奇怪的异常
- javascript - 使用javascript附加行后如何自动计算每个表行的总价格?
- git - 克隆后创建远程分支时,如何在本地签出远程分支
- java - 将Jar文件放入文件夹并打包为zip
- jquery - 如何让 jQuery 应用于 DOM 中的每个列表项
- azure - AddRedirectToWww() 重定向到错误的域
- typescript - 打字稿:定义类型的对象,但根据需要推断提供的可选道具
- gnuplot - postscript终端中的数学乳胶字体
- ngx-translate - 如何在 Angular 中翻译页面?前任。英语到阿拉伯语