python初始化后模块变量值重新启动[重复]

xmd2e60i  于 2023-02-21  发布在  Python
关注(0)|答案(2)|浏览(148)
    • 此问题在此处已有答案**:

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的常见行为吗?

khbbv19g

khbbv19g1#

您需要使用Global关键字通知__init__函数my_connection属于全局名称空间

def __init__(self, config : dict ):
    global my_connection
    my_connection = mysql.Connect( **config )
    my_connection.autocommit = True
4nkexdtk

4nkexdtk2#

你不想这样做,你必须选择变量my_connection的类型,然后坚持这个选择,它可以是:

  • 一个示例变量。它只在类的对象内部声明和使用,并且每个对象都有自己的连接。Init/close应该看起来像:
class MysqlExample(object):
      def __init__(self, config : dict ):
          self.my_connection = mysql.Connect( **config )
          self.my_connection.autocommit = True

      def close(self):
          self._endExtraction()
          self.my_connection.close()
  • 一个全局变量。2它应该被声明,初始化和关闭 * 在任何对象之外 *。3当然你有责任在任何尝试使用它之前初始化它,并在完成后关闭它。
def init_connection(config : dict ):
      global my_connection
      my_connection = mysql.Connect( **config )
      my_connection.autocommit = True

  def close_connection(self):
      my_connection.close()

  class MysqlExample(object):
      ...

你现在的代码混合了这两种方式。这意味着每个新的对象将创建一个新的全局my_connection对象(并泄漏前一个),但第一个死亡的对象将关闭全局连接。绝对是一个错误的设计...

相关问题