class SayHello(object):
    def __init__(self, text):
        self.text = text
    def __enter__(self):
        return self #必须返回对象
    def __exit__(self, exc_type, exc_value, traceback):
        self.text = "Bye!"
with SayHello("Hello") as greet:
    print(greet.text)
print(greet.text)输出:
Hello
Bye!
原文:https://blog.51cto.com/13560219/2448681