Python Error: AttributeError: __enter__ [duplicate]

寵の児 提交于 2019-11-28 05:17:21

问题


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!


回答1:


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.

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.

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 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).



来源:https://stackoverflow.com/questions/51427729/python-error-attributeerror-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!