从模块公开变量的最佳方式是什么?
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/