首页 > 解决方案 > 在python中导入函数时可以自动导入变量吗

问题描述

所以我有一个要导入的模块的功能。但我希望导入执行一些其他操作,比如一些初始化。

例如

#this is the_mod.py
name1 = 'Bob'
name2 = 'Alice'

def fun1(x):
    #some action

def fun2(y):
    #some action
#the external script
from the_mod.py import fun1
fun1(name1)

我想访问name1name2从,the_mod.py但是当我导入它的任何功能时,有没有自动导入它?

标签: pythonpython-import

解决方案


当您from在 python 导入中使用时,您会专门选择要导入的内容。所以你需要包括你的变量:

#the external script
from the_mod.py import fun1, name1
fun1(name1)

或者,通常不是一个好主意,您可以使用*which 导入所有内容:

#the external script
from the_mod.py import *
fun1(name1)

推荐阅读