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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:51:11  来源:igfitidea点击:

Python Error: AttributeError: __enter__

pythonpython-3.xcrazyflie

提问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 ParamExampleimplementation), but I'm assuming you're missing the __enter__(and probably __exit__) method on that class.

更多代码将不胜感激(特别是ParamExample实现),但我假设您缺少__enter__(并且可能__exit__)该类的方法。

When you use a withblock in python, the object in the with statement gets its __enter__method called, the block inside the withruns, 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 withblock 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 withblocks).

这与嵌套这两个上下文管理器(with块使用的对象的名称)相同。