我用谷歌搜索过但没有运气。所以让我们想象一下我有MySQL使用的连接器类__enter__
and __exit__
函数(最初与with
语句)来连接/断开与数据库的连接。
让我们有一个使用其中 2 个连接的类(例如用于数据同步)。注意:这不是我的现实生活场景,但这似乎是最简单的例子.
使其协同工作的最简单方法是这样的类:
class DataSync(object):
def __init__(self):
self.master_connection = MySQLConnection(param_set_1)
self.slave_connection = MySQLConnection(param_set_2)
def __enter__(self):
self.master_connection.__enter__()
self.slave_connection.__enter__()
return self
def __exit__(self, exc_type, exc, traceback):
self.master_connection.__exit__(exc_type, exc, traceback)
self.slave_connection.__exit__(exc_type, exc, traceback)
# Some real operation functions
# Simple usage example
with DataSync() as sync:
records = sync.master_connection.fetch_records()
sync.slave_connection.push_records(records)
Q: 可以打电话吗(有什么问题吗)__enter__
/__exit__
像这样手动?
Pylint 1.1.0 没有对此发出任何警告,我也没有找到任何关于它的文章(开头的谷歌链接)。
那么调用呢:
try:
# Db query
except MySQL.ServerDisconnectedException:
self.master_connection.__exit__(None, None, None)
self.master_connection.__enter__()
# Retry
这是一个好/坏的做法吗?为什么?