Skip to main content
 首页 » 编程设计

Python:访问另一个文件中的函数中的变量

2025年05月04日51myhome

我有两个文件:

lib.py

global var 
def test(): 
    var = "Hello!" 
    return 

测试.py

from lib import * 
test() 
print(var) 

但是尽管它们在同一个文件夹中,但当我运行 test.py 时,我收到以下错误:

Traceback (most recent call last): 
  File "C:\Test\test.py", line 5, in <module> 
    print(var) 
NameError: name 'var' is not defined 

如何在另一个文件的函数中访问这个变量?

请您参考如下方法:

您需要在其使用的范围内将变量声明为全局变量,在本例中为函数 test():

def test(): 
  global var 
  var = "Hello!" 

请注意,最后的 return 不是必需的,因为它隐含在函数的末尾。此外,var 是在模块的全局范围内声明的,因此它不会被 from lib import * 自动导入,因为它是在之后 模块已导入。

从函数返回 var 可能是跨模块使用的更好解决方案:

def test(): 
  var = "Hello!" 
  return var 
 
var = test() 
print(var) # Hello!