"AttributeError: 'NoneType' object has no attribute 'test'" using context manager

"AttributeError: 'NoneType' object has no attribute 'test'" using context manager

我有这个class:

class Tess:
    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def __enter__(self):
        print('fire away!')
        for key, value in self.kwargs.items():
            print(f"{key} and {value}")

    def __exit__(self):
        print('the end.')

    def test(self, **kwargs):        # This takes in a different dict independent of __init__
        # Also tried self.kwargs = kwargs here but doesn't change anything
        for key, value in self.kwargs.items():
            print(f"The end of {key} and {value}")
        

然后我在上下文管理器中使用它。

with Tess(foo='bar') as t:
    t.test(foo_bar='baz')

我预计输出为:

fire away!
foo and bar
The end of foo_bar and baz
the end.

它给出了:

Traceback (most recent call last):
  File "/...", line 145, in <module>
    t.test(foo_bar='baz')
AttributeError: 'dict' object has no attribute 'test'

我该如何纠正这个问题?谢谢

检查这个:

class Tess:
    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def __enter__(self):
        print('fire away!')
        for key, value in self.kwargs.items():
            print(f"{key} and {value}")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('the end')

    def test(self, **kwargs):  # This takes in a different dict independent of __init__
        # Also tried self.kwargs = kwargs here but doesn't change anything
        for key, value in self.kwargs.items():
            print(f"The end of {key} and {value}")


with Tess(foo='bar') as t:
    t.test(foo_bar='baz')

输出:

fire away!
foo and bar
The end of foo and bar
the end

我做了两处修改:

1- 为了在 as t 语句中访问 t,您应该将 return self 放在 __enter__ 中。 t 将成为 return 来自 __enter__

的任何内容

2- Python 将 exc_typeexc_valexc_tb(类型、值、回溯)传递给 __exit__ 方法,因此您应该更改您的接受这些参数的签名。