Python中with语句块用法
with语句块实际上涉及到两个python的内置方法,在python的with语句块上会执行__enter__方法,当退出这个with语句块的时候,进入__exit__方法。
tf.Session()类中有__enter__和__exit__内置方法。执行with tf.Session() as sess:时,会自动执行这两个方法。
# WithDemo是自己随便写的一个类,不是python内置的,现在只是用它来说明with的用法。
# WithDemo有__enter__和__exit__内置方法,with WithDemo() as wd4时,会执行WithDemo的__enter__和__exit__内置方法。
class WithDemo(object):
def __enter__(self):
print("进入enter方法")
return None
def __exit__(self, exc_type, exc_val, exc_tb):
print("进入exit方法")
pass
def __add__(self, other):
print("这个API是支持Python的+法,需要返回一个当前的对象!!!")
return self
if __name__ == '__main__':
wd1 = WithDemo()
wd2 = WithDemo()
print(wd1 == wd2)
# wd3 = wd1.__add__(wd2)
wd3 = wd1 + wd2
print(wd1)
print(wd3)
print(wd3 == wd1)
with WithDemo() as wd4:
print(wd4)
'''
执行结果若下所示:
False
这个API是支持Python的+法,需要返回一个当前的对象!!!
<__main__.WithDemo object at 0x0000000927F40E88>
<__main__.WithDemo object at 0x0000000927F40E88>
True
进入enter方法
None
进入exit方法
'''