简体   繁体   English

在 python 中导入函数时可以自动导入变量吗

[英]Can you auto-Import variables when you import functions in python

So I have a function from a module to be imported.所以我有一个来自要导入的模块的 function 。 But I want the import to perform some other actions like some initializing.但我希望导入执行一些其他操作,比如一些初始化。

for example例如

#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)

I want to access name1 and name2 from the_mod.py but is there anyway to import it automatically when I import any of it's functions?我想从the_mod.py访问name1name2 ,但是当我导入它的任何功能时,是否可以自动导入它?

When you use from in python imports, you specifically choose what to import.当您在 python 导入中使用from时,您具体选择要导入的内容。 So you would need to include your variable:所以你需要包括你的变量:

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

Alternatively, and not often a good idea, you can use * which imports everything:或者,通常不是一个好主意,您可以使用*导入所有内容:

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

In order to do so u must declare the variables inside the def Like为此,您必须在def Like 中声明变量

#THIS IS the_mod.py
def fun1 (x):
    name1='Bob'
    name2='Alice'
    #some action

Otherwise do it as Keldan Chapman does, like everyone does否则像凯尔丹查普曼那样做,就像每个人一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM