Python 中错误 AttributeError: __Exit__

尝试用 Python 开发新程序时出错是很常见的。 AttributeError 是 Python 中最常见的错误之一。

当属性引用或赋值失败时会发生此错误。

有时在使用 Python 程序时,您可能会收到如下所示的错误消息。

Traceback (most recent call last):
  File "<string>", line 6, in <module>
AttributeError: __exit__

这是关于 __exit__() 方法的错误。 这是一种 AttributeError。

在本文中,我们将看看如何解决这个 AttributeError: __exit__ 错误,并且我们将通过相关示例和解释来讨论这个主题。


什么是 __exit__()

要理解这个错误,我们首先需要知道 exit() 是什么以及它是如何工作的。

__exit__() 是 ContextManager 类的一个方法。 用于释放当前代码占用的资源。

此方法包含关闭资源处理程序属性的说明,以便资源可以自由供下次使用。

您需要提供类型、值和回溯作为此方法的参数。 如果发生任何异常,方法将使用这些参数。

如果发生异常或错误,方法 __exit__() 返回一个 True 值; 否则,它将返回 False。


AttributeError: __exit__ 是如何发生的

我们需要查看示例代码以了解此错误是如何发生的。 在下面共享的代码中,我们没有在 AttributeError() 类中创建 __exit__() 方法。

这个类是一个 ContextManager 类。

class AttributeError():
    def __enter__(self):
        return "This is __Enter__, if you remove this, it will generate an error."

Error = AttributeError()
with Error as Obj:
    print(Obj)

现在,如果您尝试执行上面的示例代码,您将在执行时收到以下错误。

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    with Error as Obj:
AttributeError: __exit__

如何解决 Python 中的 AttributeError: __exit__

现在我们了解了 AttributeError: __exit__ 是如何发生的。 现在我们需要了解如何解决该错误。

正如我们已经讨论过的方法 __exit__() 是 ContextManager 类的一个方法,所以我们需要在类内部定义 __exit__() 来解决这个错误。 现在我们的固定版本代码将如下所示。

class AttributeError():
    def __enter__(self):
        return "This is __Enter__; if you remove this, it will generate an error."

    def __exit__(self,exc_type, exc_val, exc_tb):
        print('This is __Exit__; if you remove this, it will generate an error.')

Error = AttributeError()
with Error as Obj:
    print(Obj)

现在,如果您执行上面的示例代码,您将看到代码已成功执行并为您提供以下输出。

This is __Enter__; if you remove this, it will generate an error.
This is __Exit__; if you remove this, it will generate an error.

%> 请注意 ,此处讨论的命令和程序是用 Python 编程语言编写的。

猜你喜欢

转载自blog.csdn.net/fengqianlang/article/details/134741409