将参数传递给 __enter__
只是了解 with 语句尤其是这篇文章的
问题是,我可以将参数传递给__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__
。这可能吗?
Just learning about with statements especially from this article
question is, can I pass an argument to __enter__
?
I have code like this:
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
I'd like to pass filename and param_dict as parameters to __enter__
. Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是的,多加一点代码就可以得到效果。
Yes, you can get the effect by adding a little more code.
不,你不能。您将参数传递给
__init__()
。No. You can't. You pass arguments to
__init__()
.接受的答案(我认为这是不正确的)表明你不能,而你应该这样做;
..虽然这是您经常会做的事情,但它并不是总是最好的解决方案,甚至不是一个解决方案,而且它绝对是不是唯一的解决方案!..
我认为你想要的是能够做类似的事情;
如果是这种情况,而且情况并不比这更复杂,那么你就可以这样做;
..这样,您仍然可以使用所需的任何参数初始化对象,并像平常一样对对象执行任何其他操作,但是当您使用该对象作为上下文管理器时,您首先调用它的 调用 函数并为上下文管理器设置一些参数。
这里重要的是准确理解上下文管理器在 Python 中的工作原理。
在 Python 中,上下文管理器是定义 enter 方法的任何对象。当您执行此操作时,会自动调用此方法;
..注意 object 后面没有几个“()”,它是一个隐式函数调用,并且不带任何参数。
您可能已经想到将参数传递给 enter from;
但这与重写 enter 不同,因为“open”不是一个对象,而是一个函数。
一个很好的练习是打开一个交互式 python 控制台并输入“open”+[ENTER]
“open”不是上下文管理器对象,而是函数。它根本没有 enter 方法,而是按以下方式定义;
..你可以用同样的方式定义你自己的上下文管理器函数,你甚至可以覆盖“open”的定义。
不过,在我看来,如果您需要创建一个对象,然后将其用作带有参数的上下文管理器(..我所做的),最好的办法是为该对象提供一个方法,该方法返回一个定义 的临时对象>输入方法,就像这样;
本例中调用链的顺序是:
喜剧演员.__init__()
->Comedian.context(args)
->Roaster.__enter__()
我觉得这个答案在很多地方都缺失了,所以我添加了它。
编辑:将“
return self
”添加到Comedian.__call__
,如@MarkLoyman所指出的The accepted answer (Which I feel is incorrect) states that you CAN'T, and that you should instead do;
..and while this is often what you would do, it is not always the best solution, or even a solution, and it is definitely not the only solution!..
I assume that what you want is to be able to do something similar to;
If this is the case, and it is not more complicated than that, then you can just do;
..That way you can still initialize the object with any arguments that you want, and do any other stuff with the object like you would usually, but when you go to use the object as a context manager you first call its call function and set up some args for the context manager.
The important thing here is to understand exactly how context managers work in Python.
In Python a context manager is any object that defines an enter method. This method is called automatically when you do;
..Notice how object doesn't have a couple of "()" after it, it is an implicit function call, and it doesn't take any arguments.
You might have gotten the idea of passing arguments to enter from;
But this is different from overriding enter, as "open" is not an object, but a function.
A good exercise is to open an interactive python console and type "open" + [ENTER]
"open" is not a context manager object, but function. It doesn't have an enter method at all, instead it is defined in the following way;
..you can define your own context manager functions in the same way, you can even override the definition of "open".
IMO though, the best thing to do if you need to create an object and then later use it as a context manager with arguments (..what I do) is to give the object a method that returns a temporary object that defines an enter method, like so;
The order of the call-chain in this example is;
Comedian.__init__()
->Comedian.context(args)
->Roaster.__enter__()
I felt like this answer was missing from the lot, so I added it.
EDIT: Added "
return self
" toComedian.__call__
as pointed out by @MarkLoyman您可以使用 contextmanager 装饰器来传递参数:
https://docs.python .org/3/library/contextlib.html#contextlib.contextmanager
恕我直言,我发现使用
contextmanager
可以提供参数,但无法将它们提供给__enter__
You can use the contextmanager decorator to pass arguments:
https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager
IMHO, I find confusing that using
contextmanager
you can provide arguments, but you cannot provide them to__enter__
您不只是通过类构造函数将值传递给 __init__ 吗?
Wouldn't you just pass the values to
__init__
via the class constructor?我认为使用contextlib.contextmanager(本机包)是一个好主意。
更多详情,请参见下文。
一个简单的
输出
示例
它
关于
contextmanager
上下文管理器(基本上)执行三件事:
I think to use the
contextlib.contextmanager
(native package) is a good idea.More details, see as follows.
a simple example
output
example of yours
output
About
contextmanager
A context manager does (basically) three things:
您可以在实例中保存状态:(PS我不推荐这样做,因为它会导致意大利面条代码)
这是测试:
You can save the state in the instance: (PS I don't recommend this as it leads to spaghetti code)
Here is the test: