要使用 with 语句,首先要明白上下文管理器这一律念。有了上下文管理器,with 语句才能工做。 下面是一组与上下文管理器和with 语句有关的概念.code
上下文管理协议(Context Management Protocol)orm
上下文管理器(Context Manager)对象
运行时上下文(runtime context)utf-8
上下文表达式(Context Expression)it
语句体(with-body)io
# -*- coding: utf-8 -*- class WithTest(object): def __init__(self, name): self.name = name def __enter__(self): # 进入的时候载入该方法,return 类自己 print "Frist Step:Enter Function" return self def __exit__(self, exc_type, exc_val, exc_tb): # 退出的时候执行该方法, 上面的参数是必备的.能够在这里作一些判断、清理和抱错等工做 print "Last Step: exit function" def printf_name(self): # 类方法.使用as f 后能够直接用f调用 return "Your Name is {}".format(self.name) with WithTest("Hero") as f: print f.name print f.printf_name()