Python interview question eleven (what is context? with the context manager principle?)

  • with is often used to open files, using with can automatically close even if an error occurs
  • What is context?
    • The context is actually blunt, and the context of the article is a meaning, in a bit more popular, I think it is better to call the environment
    • Although the context is called a context, it is usually only the above in the program, but it is just a nice call to the context. .
    • There are ups and downs in process interruption in the operating system, but do n’t delve into this deep question.
    • Any object that implements the enter () and exit () methods can be called a context manager. The
      context manager object can use the with keyword. Obviously, the file object also implements the context manager.
  • So how do file objects implement these two methods? We can simulate and implement an own file class and
    let the class implement the enter () and exit () methods.
class File():

    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        print("entering")
        self.f = open(self.filename, self.mode)
        return self.f

    def __exit__(self, *args):
        print("will exit")
        self.f.close()
        
# __enter__() 方法返回资源对象,这里就是你将要打开的那个文件对象,
# __exit__() 方法处理一些清除工作。

with File('out.txt', 'w') as f:
    print("writing")
    f.write('hello, python')
    
# 你就无需显示地调用 close 方法了,由系统自动去调用,哪怕中间遇到异常 close 方法也会被调用。

Published 44 original articles · liked 0 · visits 1226

Guess you like

Origin blog.csdn.net/weixin520520/article/details/105451434