次のinitメソッドを持つ DB クラスの場合:
class DB:
def __init__(self, dbprops):
self.dbprops = dbprops
self.conn = self.get_connection(self.dbprops)
debug("self.conn is %s" %self.conn)
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.conn is None:
self.close()
そして、次のようにそれを呼び出すクライアントメソッドの場合:
with DB(self.dbprops) as db:
if not db:
raise Exception("Db is None inside with")
return db.get_cmdline_sql()
出力にはデバッグ メッセージが表示されます。つまり、initメソッドが正常に呼び出されました。
File "./classifier_wf.py", line 28, in get_cmdline_mysql
raise Exception("Db is None inside with")
例外: Db is None inside with with
更新: DB オブジェクトを返すようにenterメソッドを修正しました。しかし、それを呼び出す方法についての助けが必要です:
def __enter__(self, dbprops):
return DB(dbprops)
単一のパラメーターで呼び出すと、明らかに機能しません。
with DB(dbprops) as db:
TypeError: __enter__() takes exactly 2 arguments (1 given)
「自己」は自動的に入力されるはずなので、今はフォローしません..