python - 在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)
我想访问name1
和name2
从,the_mod.py
但是当我导入它的任何功能时,有没有自动导入它?
解决方案
当您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)
推荐阅读
- arduino - 我尝试的代码无法运行 blcd 电机
- angular - 编辑父组件表单时如何测试角度子组件显示
- javascript - 不变违规:元素类型无效:期望字符串(内置组件)或类/函数(复合组件)但得到:对象
- android - 带有音频文件的多个 ImageView
- java - 从firebase检索数据到arraylist的问题
- html - How can I make horizontal scroll bar only code block in ?
- c# - .Net Core 2.2 C# HttpClient.GetAsync 有时在高负载后停止工作?
- android - 为什么很久没显示通知
- node.js - 使用 Csurf 库时,csurf 令牌未保存在 Safari 中
- wordpress - 具有相同名称的现有页面时重写自定义帖子类型的规则