首页 > 解决方案 > 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

我无法理解这种情况。

有人可以帮我吗?

感谢您的意见。

标签: pythonglobal-variablesreturn-valueuser-defined-functionscalling-convention

解决方案


Python 没有真正的全局变量,只有模块级全局变量。访问的是,Z而不是你设置的。getZgetZ.Z__main__.Zmain2.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)

推荐阅读