Python 错误:属性错误:__enter__
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51427729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Error: AttributeError: __enter__
提问by Alex Quinto
I receive the attribute error when I try to run the code.
当我尝试运行代码时收到属性错误。
with ParamExample(URI) as pe:
with MotionCommander(pe, default_height=0.3)as mc:
This is where the error occurs.
这就是错误发生的地方。
Traceback (most recent call last):
File "test44.py", line 156, in <module>
with ParamExample(URI) as pe:
AttributeError: __enter__
That is the traceback that I receive in my terminal. If you need to see more of my code, please let me know. Any help is appreciated, thank you!
这是我在终端中收到的回溯。如果您需要查看我的更多代码,请告诉我。任何帮助表示赞赏,谢谢!
回答by BowlingHawk95
More code would be appreciated (specifically the ParamExample
implementation), but I'm assuming you're missing the __enter__
(and probably __exit__
) method on that class.
更多代码将不胜感激(特别是ParamExample
实现),但我假设您缺少__enter__
(并且可能__exit__
)该类的方法。
When you use a with
block in python, the object in the with statement gets its __enter__
method called, the block inside the with
runs, and then the __exit__
gets called (optionally with exception info if one was raised). Thus, if you don't have an __enter__
defined on your class, you'll see this error.
当您with
在 python 中使用块时, with 语句中的对象会__enter__
调用其方法,with
运行中的块,然后__exit__
调用(如果引发异常信息,则可选)。因此,如果您__enter__
的类没有定义,您将看到此错误。
Side note: you need to either indent the second with
block so it's actually inside the first, OR replace these two lines with
旁注:您需要缩进第二个with
块,使其实际上位于第一个块内,或者将这两行替换为
with ParamExample(URI) as pe, MotionCommander(pe, default_height=0.3) as mc:
which is the same as nesting these two context managers (the name of the objects used by with
blocks).
这与嵌套这两个上下文管理器(with
块使用的对象的名称)相同。