#coding=UTF-8
import logging
from tensorflow.python.framework import device
import functools
import six
import abc
class Test(object):
def __init__(self):
print("hello")
def __enter__(self):
print("enter")
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
#可以把自己写的资源对象用于with语句
with Test() as t:
print("test")
使用contextlib的contextManager 结合 yield
#coding=UTF-8
import logging
from tensorflow.python.framework import device
import functools
import six
import abc
from contextlib import contextmanager
class Test(object):
def __init__(self):
print("hello")
def t_print(self):
print("tpring")
@contextmanager
def query():
# enter
print("enter")
t = Test()
yield t
# exit
print("exit")
with query() as t:
t.t_print()