语句集变量为None

Kip*_*ipi 4 python syntax

我正在尝试运行此代码:

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
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

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'
Run Code Online (Sandbox Code Playgroud)

我的语法有什么问题?

mat*_*yce 10

您需要self__enter__以下地址返回:

def __enter__(self):
    print "enter"
    return self
Run Code Online (Sandbox Code Playgroud)

您的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)
Run Code Online (Sandbox Code Playgroud)

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