一些背景知识:我在一家大银行工作,我正在尝试重用一些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)
关于如何正确地做这件事有什么建议吗?
使用
with
协议假定with
中使用的对象实现context manager protocol。基本上这意味着类定义应该定义
__enter__()
和__exit__()
方法。如果使用没有这些属性的对象,python将抛出一个AttributeError
来抱怨缺少的__exit__
属性。该错误意味着
BacktestingDatabaseHelper
不是设计用于with
语句的。听起来类testingResource
和BacktestingDatabaseHelper
彼此不兼容(可能您的common.databaseHelper
版本已经过时)。由于无法更改
with
语句,因此必须添加一个派生自BacktestingDatabaseHelper
的类,该类将添加适当的__enter__()
和__exit__()
函数,并改用它。下面是一个尽量接近原稿的例子:
但问题是,我不确定
__enter__
应该返回什么。例如,如果采用MySQLdb
,则连接的上下文管理器将创建一个表示一个事务的游标。如果这里也是这样的话,就得想办法。。。相关问题 更多 >
编程相关推荐