Python basics with...as statement

1.1 The role of the with statement

The with statement can automatically manage the context resources. Regardless of the reason, jumping out of the with block can ensure that the file is closed correctly, so as to achieve the purpose of releasing resources.

Simple meaning: it can be closed without manual close(), and resources can be released automatically

with open("new.txt") as f:
    data = f.read()
    print(data)

1.2 How the with statement works

Definition principle: The object evaluated by with must have an __enter__() method and an __exit__() method

Steps:

1. After the statement following with is evaluated, the __enter__() method of the returned object is called, and the return value of this method will be assigned to the variable after as.

2. When all the code blocks behind with are executed, the __exit__() method of the returned object will be called

class MyContentMgr:
    def __enter__(self):
        print("enter方法被调用执行了")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit方法被调用执行了")

    def show(self):
        print("show方法被调用执行了")


with MyContentMgr() as file:
    file.show()

1.3 The with statement automatically handles exceptions

The real power of with is that it can handle exceptions. The __exit__ method has three parameters, exc_type, exc_val, and exc_tb. These parameters are quite effective in exception handling.

In the above code, when the show() function is called and an error is reported, it will not affect the automatic call of the __exit__ method

Guess you like

Origin blog.csdn.net/xiao__dashen/article/details/125194516