首页 > 解决方案 > Python 错误:AttributeError:__enter__

问题描述

当我尝试运行代码时收到属性错误。

    with ParamExample(URI) as pe:
    with MotionCommander(pe, default_height=0.3)as mc:

这是发生错误的地方。

Traceback (most recent call last):
File "test44.py", line 156, in <module>
with ParamExample(URI) as pe:
AttributeError: __enter__

那是我在终端中收到的回溯。如果您需要查看我的更多代码,请告诉我。任何帮助表示赞赏,谢谢!

标签: pythonpython-3.xcrazyflie

解决方案


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

当您在 python 中使用with块时,with 语句中的对象会__enter__调用它的方法,with运行内部的块,然后__exit__调用(如果引发了异常信息,则可选地带有异常信息)。因此,如果你的类没有__enter__定义,你会看到这个错误。

旁注:您需要缩进第二个with块,使其实际上在第一个块内,或者将这两行替换为

with ParamExample(URI) as pe, MotionCommander(pe, default_height=0.3) as mc:

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


推荐阅读