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

标签 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

我得到这个错误:

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/

相关文章:

python - 为什么这个 Sqlite 日期比较有效?

python - Django模板: Exclude request.用户显示用户列表

C 参数数组声明符

javascript - 添加OnError后出现异常错误

syntax - RAML 1.0 - 单个响应的多个示例

python - 使用 PuLP 优化器实现具有额外弹性约束的装箱问题

Python C API : How to check if an object is an instance of a type

python - 如何使按钮图像拉伸(stretch)、透明、宽度高度完全缩放适合?

java - C 就像在 java 中使用整数一样?

PHP - 类数组中带有括号的奇怪语法错误