table of Contents
@
1. Description
Manager context
used here with open operating files, so the file object implements the automatic release of resources. We can also customize the context manager by __enter __ () and __exit __ () method of operation of these two magic file from defined
when there is a scene context of use, such as open a thing to be shut down, files and other resources such as , can be used in this manner to define a context manager
2. Code
class File():
def __init__(self,filename,mode):
self.filename = filename
self.mode = mode
def __enter__(self):
print("__enter__")
self.f = open(self.filename,self.mode,encoding="utf-8")
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
self.f.close()
with File("魔方方法.py","r") as f:
print(f.read())
About the Author
Personal blog site
personal GitHub address
individual public number: