2

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

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是一个对象,所以我不确定如何声明它以使其暴露。

4

2 回答 2

5

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

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")
于 2013-06-28T03:48:24.050 回答
2

默认情况下,在模块级别创建的任何变量都是“公开的”。

因此,像这样的模块将具有三个公开的变量:

configpath = '$HOME/.config'

class Configuration(object):

    def __init__(self, configpath):
        self.configfile = open(configpath, 'rb')

config = Configuration(configpath)

变量configpathConfigurationconfig。所有这些都可以从其他模块导入。您也可以将configs访问configfileconfig.configfile.

您还可以通过这种方式全局访问配置文件:

configpath = '$HOME/.config'
configfile = None

class Configuration(object):

    def __init__(self, configpath):
        global configfile
        configfile = open(configpath, 'rb')

config = Configuration(configpath)

但是这有很多棘手的问题,就好像你configfile从另一个模块得到一个句柄,然后从Configuration你原来的句柄中替换它不会改变。因此,这只适用于可变对象。

在上面的示例中,这意味着configfile以这种方式作为全局使用不会很有用。但是,config像这样使用可以很好地工作。

于 2013-06-29T12:55:46.640 回答