python - 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__
那是我在终端中收到的回溯。如果您需要查看我的更多代码,请告诉我。任何帮助表示赞赏,谢谢!
解决方案
更多代码将不胜感激(特别是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
块使用的对象的名称)相同。
推荐阅读
- android - Android PDF 阅读器,带有额外的页码意图
- python - 如何访问一个对象的方法/属性以在 Python 中的另一个对象中使用?
- terraform - 如何在 terraform 脚本的资源中访问 terraform 提供程序属性?
- python-3.x - 为什么while不适用于if语句和else
- swift - 如何编写有条件发布的发布者?
- python - 在 Python 与 C++ 中为 C 库创建 GUI
- c++ - 为什么 scanf() 输入后不换行?
- java - MongoTemplate 拉取查询在 mongo shell 和 spring mongoTemplate 中不起作用
- javascript - 为什么我的状态显示在我的控制台日志中,而不是我的 HTML?
- sql - 选择一个值,然后在同一个表中选择这个值并在 SQL 中进行比较