下面例子可以具体说明with如何工作:
#!/usr/bin/env python
# with_example01.py
class Sample:
def __enter__(self):
print "In __enter__()"
return "Foo"
def __exit__(self, type, value, trace):
print "In __exit__()"
def get_sample():
return Sample()
with get_sample() as sample:
print "sample:", sample
运行代码,输出如下
bash-3.2$ ./with_example01.py
In __enter__()
sample: Foo
In __exit__()
网友评论