python with妙用

时间:2023-01-07 11:01:00
class aa():
def bb(self):
print("hhhh")
return "hello world" def __enter__(self): # 必须有__enter__
print("enter")
return self def cc(self):
print("www") def __exit__(self, exc_type, exc_val, exc_tb): # 必须有结束__exit__
print("exit") def ll():
with aa() as a:
return a.bb() res = ll()
print(res)

结果:

enter
hhhh
exit
hello world