我在Python脚本中遇到了一些导入模块的问题.我将尽我所能来描述错误,为什么我遇到它,以及为什么我要用这种特殊的方法来解决我的问题(我将在一秒钟内描述):
假设我有一个模块,我在其中定义了一些实用函数/类,它们引用了将在其中导入此辅助模块的命名空间中定义的实体(让"a"成为这样的实体):
模块1:
def f():
print a
Run Code Online (Sandbox Code Playgroud)
然后我有主程序,其中定义了"a",我想导入这些实用程序:
import module1
a=3
module1.f()
Run Code Online (Sandbox Code Playgroud)
执行程序将触发以下错误:
Traceback (most recent call last):
File "Z:\Python\main.py", line 10, in <module>
module1.f()
File "Z:\Python\module1.py", line 3, in f
print a
NameError: global name 'a' is not defined
Run Code Online (Sandbox Code Playgroud)
过去(两天前,呃)已经提出了类似的问题,并提出了几种解决方案,但我并不认为这些问题符合我的要求.这是我的特定背景:
我正在尝试创建一个连接到MySQL数据库服务器并使用GUI显示/修改数据的Python程序.为清洁起见,我在一个单独的文件中定义了一堆辅助/实用的MySQL相关函数.但是它们都有一个公共变量,我最初在实用程序模块中定义了它,它是MySQLdb模块中的游标对象.后来我意识到应该在主模块中定义游标对象(用于与数据库服务器通信),这样主模块和导入其中的任何东西都可以访问该对象.
最终结果将是这样的:
utilities_module.py:
def utility_1(args):
code which references a variable named "cur"
def utility_n(args):
etcetera
Run Code Online (Sandbox Code Playgroud)
我的主要模块:
program.py:
import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor() #cur is defined!
from …Run Code Online (Sandbox Code Playgroud) 假设您有 的Vec实例的两个集合(此处为简单起见)T,以及一个用于计算这些集合中的元素是否出现在其中一个或两个集合中的函数:
// With lifetimes not yet annotated
fn comm(left: &Vec<T>, right: &Vec<T>) -> Vec<(Tag, &T)> {}
enum Tag {
Left,
Both,
Right,
}
Run Code Online (Sandbox Code Playgroud)
comm(l,r) 保证返回的引用指向left集合的元素,无论T是出现在leftonly中还是 T出现在 Both 中。
然而,因为有些T可能出现在rightonly 中,所以函数的完整签名必须如下所示:
fn comm<'a, 'b, 'c>(left: &'a Vec<T>, right: &'b Vec<T>) -> Vec(Tag, &'c T)
where
'a: 'c,
'b: 'c,
Run Code Online (Sandbox Code Playgroud)
(tag, &T)那么,实际的问题是:我知道,在返回的元组之一中comm, if tag == Left or tag == Both, …