python - 如何在 Python 模块中公开变量?

标签 python

从模块公开变量的最佳方式是什么?

import otherDBInterface as odbi

def create(host):
    global connection
    global cursor
    connection = odbi.connect(host)
    cursor = connection.cursor()
    ...

我想在模块中公开 cursor 变量,这样我就可以执行类似 mydb.cursor.execute("select * from foo;") 的操作。我认为使用 global 关键字可以做到这一点,但没有这样的运气。 cursor 是一个对象,所以我不确定如何声明它以便将其公开。

最佳答案

您可以将您的连接信息包装在一个类中

class Database:

    def __init__(self, **kwargs):

        if kwargs.get("connection") is not None:

            self.connection = kwargs["connection"]

        elif kwargs.get("host") is not None:

            self.connection = odbi.connect(host)
            self.cursor = self.connection.cursor()

mydb = Database(host="localhost")

results = mydb.cursor.execute("select * from foo")

#or use it with a connection

mydb = Database(connection="localhost")

results = mydb.cursor.execute("select * from foo")

关于python - 如何在 Python 模块中公开变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17356862/

相关文章:

python - 如何将像素坐标与 imshow() 命令一起使用,以便从 python 中适合图像的特定部分生成图像?

python - 如何滚动不活动的 Tkinter 列表框?

python - python 的“ self ”与 cpp/c# 的 'this'

python - django 从 git 安装依赖项

python - Django ModelAdmin get_form() 没有设置字段属性

python - 心理学/Postgres : Connections hang out randomly

python - 使用正确的密码解密受 aes-256 位保护的 pdf

python - 通过渲染变量的中间来修改django模板中的变量

python - PyQt5 项目结构和 PyInstaller ModuleNotFoundError

javascript - 如何在 Bokeh 中创建加载指示器?