![](/img/trans.png)
[英]Getting "NoneType object has no attribute" when using "with ... as" for custom context manager
[英]“AttributeError: 'NoneType' object has no attribute 'test'” using context manager
我有這門課:
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
將是您從__enter__
返回的任何__enter__
2- Python 將exc_type
、 exc_val
、 exc_tb
(類型、值、回溯)傳遞給__exit__
方法,因此您應該更改簽名以接受這些參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.