【发布时间】:2016-05-31 05:04:05
【问题描述】:
这没问题(为简洁起见省略了一些代码):
# main.py
cursor = db.cursor()
cursor.execute('foo')
这样:
# other.py
def do_something(script, cursor):
cursor.execute(script)
# main.py
from other import do_something
cursor = db.cursor()
do_something('foo', cursor)
但是(据我了解)函数的“较低”范围应该能够访问“较高”(全局?)范围的游标——为什么我需要将游标作为参数传递给我的函数?所以我尝试了这个:
# other.py
def do_something(script):
cursor.execute(script)
# main.py
from other import do_something
cursor = db.cursor()
do_something('foo')
返回:
NameError: global name 'cursor' is not defined
我认为“可能对游标运行查询是写入操作,而不是读取”并尝试:
# other.py
def do_something(script):
global cursor
cursor.execute(script)
# main.py
from other import do_something
cursor = db.cursor()
do_something('foo')
同样的错误。我错过了什么?
编辑:听起来“如何使变量名在不同模块中全局化”是错误的问题。正确的问题 - 如果我有一个主处理程序、一个 SQL 游标和一个包含常用函数的文件,我应该如何构建我的文件/导入?
【问题讨论】:
标签: python python-2.7 mysql-python