Python缺少exit方法

2024-04-16 20:11:01 发布

您现在位置:Python中文网/ 问答频道 /正文

一些背景知识:我在一家大银行工作,我正在尝试重用一些Python模块,我不能更改,只能导入。我也没有选择安装任何新的实用程序/函数等(在Linux上运行Python2.6)。

我现在有这个:

在我的模块中:

from common.databaseHelper import BacktestingDatabaseHelper

class mfReportProcess(testingResource):
    def __init__(self):
        self.db = BacktestingDatabaseHelper.fromConfig('db_name')

“testingResource”类中调用的方法之一具有以下内容:

 with self.db as handler:

而这一点又是:

with self.db as handler:
AttributeError: 'BacktestingDatabaseHelper' object has no attribute '__exit__'

而且,实际上,“BacktestingDatabaseHelper”类中没有__exit__方法,我无法更改该类。

然而,我试图重用的代码对于其他应用程序非常有效-有人知道为什么我会出现这个错误而没有其他人知道吗? 有什么方法可以在本地定义__exit__

多谢提前。

编辑以添加:

我试图将自己的类添加到setup DB access,但无法使其正常工作-将此添加到我的模块:

class myDB(BacktestingDatabaseHelper): 
    def __enter__(self): 
        self.db = fromConfig('db_name') 
    def __exit__(self): 
        self.db.close() 

并添加:

self.db = myDB 

进入我的主类的init属性,但我得到这个错误:

with self.db as handler:
TypeError: unbound method __enter__() must be called with myDB instance as first argument (got nothing instead)

关于如何正确地做这件事有什么建议吗?


Tags: 模块方法nameselfdbinitdefas
3条回答

使用with协议假定with中使用的对象实现context manager protocol

基本上这意味着类定义应该定义__enter__()__exit__()方法。如果使用没有这些属性的对象,python将抛出一个AttributeError来抱怨缺少的__exit__属性。

该错误意味着BacktestingDatabaseHelper不是设计用于with语句的。听起来类testingResourceBacktestingDatabaseHelper彼此不兼容(可能您的common.databaseHelper版本已经过时)。

由于无法更改with语句,因此必须添加一个派生自BacktestingDatabaseHelper的类,该类将添加适当的__enter__()__exit__()函数,并改用它。

下面是一个尽量接近原稿的例子:

class myDB(BacktestingDatabaseHelper): 
    def __enter__(self): 
        return self
    def __exit__(self): 
        self.db.close()
    def fromConfig(self, name):
        x = super(myDB, self).fromConfig(name)
        assert isinstance(x, BacktestingDatabaseHelper)
        x.__class__ = myDB # not sure if that really works
[...]
self.db=myDB.fromConfig('tpbp')

但问题是,我不确定__enter__应该返回什么。例如,如果采用MySQLdb,则连接的上下文管理器将创建一个表示一个事务的游标。如果这里也是这样的话,就得想办法。。。

相关问题 更多 >