从python中的另一个文件访问函数变量
我有两个文件从python中的另一个文件访问函数变量,python,function,file,variables,Python,Function,File,Variables,我有两个文件File1和File2。在File1中,我有一个函数detect()定义为: def detect(): s = // some operations 我需要在File2中访问此变量s 我曾尝试将变量声明为global,但它不起作用 我如何在不创建类的情况下访问变量,或者使用\uuuu main\uuuu访问变量?函数detect必须运行以初始化其局部变量 def detect(): detect.tmp = 1 def b(): print(detect
File1
和File2
。在File1
中,我有一个函数detect()
定义为:
def detect():
s = // some operations
我需要在File2
中访问此变量s
我曾尝试将变量声明为global
,但它不起作用
我如何在不创建类的情况下访问变量,或者使用
\uuuu main\uuuu
访问变量?函数detect必须运行以初始化其局部变量
def detect():
detect.tmp = 1
def b():
print(detect.tmp)
detect()
b()
当然,您可以将一个python文件作为python模块导入,并调用其函数,如
from File1 import detect
print(detect.tmp)
让
detect()
函数返回变量怎么样?一种方法是让detect函数返回s值。然后你可以在任何地方调用detect。我不能调用函数,因为它可能执行其他操作,但我只需要访问该变量。我需要调用函数才能访问我不想访问的变量。不调用函数的局部变量就访问函数的局部变量没有任何意义。这个中的X是什么?s
在实际计算detect()
之前没有值,所以您所要求的没有意义。