- 此问题在此处已有答案**:
Using global variables in a function(25个答案)
6小时前关门了。
我尝试在python中创建一个全局变量,但似乎我对这个概念理解不深。我在一个名为mysql_example
的模块中创建了一个my_connection
变量,然后我在MysqlExample
类中初始化了它,但之后,该值被清除。我的mysql_example
模块有以下代码:
import datetime
import mysql.connector as mysql
my_connection = None
class MysqlExample(object):
def __init__(self, config : dict ):
my_connection = mysql.Connect( **config )
my_connection.autocommit = True
def close(self):
self._endExtraction()
my_connection.close()
def __enter__(self):
self._id_extraction = self._startExtraction()
return self
def __exit__(self, type, value, tb ):
self.close()
def _startExtraction(self):
cur = my_connection.cursor()
cur.execute( '''select * from simple_test''' )
return cur.lastrowid
def _endExtraction(self):
self._lock.acquire()
cur = my_connection.cursor()
cur.execute('''select * from simple_test''',
{ 'id_extraction' : self._id_extraction,
'end_date' : datetime.datetime.now() } )
self._lock.release()
主调用是这样的:
with MysqlExample({ "host" : "XXXX",
"database" : "XXXXX",
"user" : "XXXXX",
"password" : "super-secret-password" }) as my_example:
print("hello")
代码显示的错误为:
AttributeError: 'NoneType' object has no attribute 'cursor'
这是因为值my_connection
在每次方法调用中都被重新初始化,这是python的常见行为吗?
2条答案
按热度按时间khbbv19g1#
您需要使用Global关键字通知
__init__
函数my_connection属于全局名称空间4nkexdtk2#
你不想这样做,你必须选择变量
my_connection
的类型,然后坚持这个选择,它可以是:你现在的代码混合了这两种方式。这意味着每个新的对象将创建一个新的全局
my_connection
对象(并泄漏前一个),但第一个死亡的对象将关闭全局连接。绝对是一个错误的设计...