gpt4 book ai didi

python - 将参数传递给 __enter__

转载 作者:IT老高 更新时间:2023-10-28 21:46:59 26 4
gpt4 key购买 nike

刚刚学习 with 语句 especially from this article

问题是,我可以将参数传递给 __enter__ 吗?

我有这样的代码:

class clippy_runner:
def __enter__(self):
self.engine = ExcelConnection(filename = "clippytest\Test.xlsx")
self.db = SQLConnection(param_dict = DATASOURCES[STAGE_RELATIONAL])

self.engine.connect()
self.db.connect()

return self

我想将文件名和 param_dict 作为参数传递给 __enter__。这可能吗?

最佳答案

可以,多加一点代码就可以达到效果。


#!/usr/bin/env python

class Clippy_Runner( dict ):
def __init__( self ):
pass
def __call__( self, **kwargs ):
self.update( kwargs )
return self
def __enter__( self ):
return self
def __exit__( self, exc_type, exc_val, exc_tb ):
self.clear()

clippy_runner = Clippy_Runner()

print clippy_runner.get('verbose') # Outputs None
with clippy_runner(verbose=True):
print clippy_runner.get('verbose') # Outputs True
print clippy_runner.get('verbose') # Outputs None

关于python - 将参数传递给 __enter__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5109507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com