最近遇到一个Python的面试题,挺有意思,虽然很简单,但是猛的一想还真不会呢,先上题:
编写一个函数或者类实现以下功能:
with f() as f:
print("hello world")
# out:
start
hello world
end
应该是可以想到python里面的上下文管理器;
Pyhton class 里有__enter__ 和__exit__,他们是可以实现这个,
class F(object):
def __enter__(self):
print("start")
def __exit__(self, exc_type, exc_val, exc_tb):
print("end")
with F() as f:
print("hello world")
这样是可以正确输出: start hello world end
如果用函数是否可以实现呢?
from contextlib import contextmanager
@contextmanager
def f():
print('start')
yield
print('end')
with f() as f:
print('hello')