【问题标题】:Accessing global cursor from within function从函数内部访问全局游标
【发布时间】: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


    【解决方案1】:

    试试这个代码

    # other.py
    def do_something(script):
      global cursor
      cursor.execute(script)
    
    # main.py
    from other import do_something
    import other
      other.cursor = db.cursor()
      do_something(script)
    

    我的英文不好,你可以看看这些答案

    【讨论】:

    • 有趣!所以听起来我目前的结构可能是错误的方式(见编辑)。我会看看这些答案,看看是否能找到更好的方法。
    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多