python with as

今天使用进程时使用了multipressing中的Lock,使用一次with Lock,很有意思.

python 中对with的处理思想四with所求的值的对象必须有一个__enter__()方法,一个__exit__()方法.

紧跟with后边的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将返回值给as后面的变量.

当with后面的代码块全部被执行完毕之后,将调用前面返回对象的__exit__()方法.

# class Sample:
#     def __enter__(self):
#         print("in __enter()")
#         return 'Foo'
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print('in __exit__()')
#
# def get_sample():
#     return Sample()
# with get_sample() as sample:
#     print('sample:',sample)
in __enter__()
sample: Foo
in __exit__()

__enter__()方法被执行

__enter__()方法返回值  - 这个例子中的是'Foo',赋值给变量'sample
执行代码块,打印变量'sample'的值为'Foo'

__exit__的方法被调用  

with的Sample类的__exit__方法有三个参数 -exc_type, exc_val, exc_tb,

# class Sample:
#     def __enter__(self):
#         return self
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print('type:',exc_type)
#         print('type:',exc_val)
#         print('type:',exc_tb)
#     def do_something(self):
#         bar = 1/0
#         return bar + 10
# with Sample() as sample:
#     sample.do_something()

with 会自动调用她的类,然后执行__enter__,执行with后的方法和with下的方法,然后执行__exit__函数,这个函数会自动关闭,回收资源等.  

  

原文地址:https://www.cnblogs.com/lnrick/p/9374728.html