gpt4 book ai didi

python - With 语句将变量设置为 None

转载 作者:太空狗 更新时间:2023-10-30 01:51:06 25 4
gpt4 key购买 nike

我正在尝试运行这段代码:

class A:
def __enter__(self):
print "enter"
def __exit__(self, *args):
print "exit"
def __init__(self, i):
self.i = i
with A(10) as a:
print a.i

我得到这个错误:

enter
exit
Traceback (most recent call last):
File ".last_tmp.py", line 9, in <module>
print a.i
AttributeError: 'NoneType' object has no attribute 'i'

我的语法有什么问题?

最佳答案

您需要从 __enter__ 返回 self:

def __enter__(self):
print "enter"
return self

您的 with 语句实际上等同于:

a = A(10).__enter__()  # with A(10) as a:
try:
print a.i # Your with body
except:
a.__exit__(exception and type)
raise
else:
a.__exit__(None, None, None)

所以,你需要返回一些东西,否则a会有None的值(默认返回值),而None不会有一个名为 i 的属性,所以你会得到一个 AttributeError

关于python - With 语句将变量设置为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com