Rhy*_*ich 0 python callable with-statement
关于为什么在 Python 3.5with语句中不可调用的可调用对象的任何押韵或原因?
class Seriously(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print("Enter " + self.name)
def __call__(self):
print("Call " + self.name)
def __exit__(self, type, value, traceback):
print("Exit " + self.name)
a = Seriously('a')
a.__enter__()
a()
a.__enter__()
with Seriously('b') as b:
b()
Run Code Online (Sandbox Code Playgroud)
严重产生
Enter a
Call a
Enter a
Enter b
Exit b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-91a5d11e1b2e> in <module>()
18
19 with Seriously('b') as b:
---> 20 b()
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
我在PEP 343 中缺少什么?
您不会从该__enter__方法返回任何内容,该方法由 python 编译器转换为None. 您应该从 中返回要受as子句约束的值__enter__。
该with声明被删除为
mgr = (EXPR)
exit = type(mgr).__exit__
value = type(mgr).__enter__(mgr) ### <--- usually the same as mgr.__enter__()
exc = True
try:
try:
VAR = value ### <--- value returned by __enter__, VAR from with/as statement
BLOCK
except:
exc = False
if not exit(mgr, *sys.exc_info()):
raise
finally:
if exc:
exit(mgr, None, None, None)
Run Code Online (Sandbox Code Playgroud)
(来自您在问题中链接的 PEP)。
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |