程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Advanced Series (17)

編輯:Python

Context manager (Context managers)

The context manager allows you to , Allocate and release resources precisely .

The most extensive case of using context manager is with Statement .

Imagine that you have two related operations that need to be performed in pairs , Then put a piece of code between them .

Context manager is designed to let you do this . for instance :

with open('some_file', 'w') as opened_file:
    opened_file.write('Hola!')

The above code opens a file , Wrote some data into it , Then close the file . If an exception occurs when writing data to a file , It will also try to close the file . The above code is equivalent to this one :


file = open('some_file', 'w')
try:
    file.write('Hola!')
finally:
    file.close()

When compared with the first example , We can see , By using with, A lot of boilerplate code (boilerplate code) Has been eliminated . This is it. with The main advantages of statements , It ensures that our files will be closed , Instead of focusing on how nested code exits .

A common use case for context manager , It is the locking and unlocking of resources , And close open files ( As I've shown you ).

Let's see how to implement our own context manager . This will give us a more complete understanding of what is happening behind these scenes .

Class based implementation

A class of context manager , At least define __enter__ and __exit__ Method .

Let's construct our own context manager for opening files , And learn the basics .

class File(object):
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method)
    def __enter__(self):
        return self.file_obj
    def __exit__(self, type, value, traceback):
        self.file_obj.close()

By defining __enter__ and __exit__ Method , We can do it in with Use it in statements . Let's try :


with File('demo.txt', 'w') as opened_file:
    opened_file.write('Hola!')

our __exit__ The function takes three arguments . These parameters are for each context manager class __exit__ Methods are necessary . Let's talk about what happened at the bottom .

    1. with The statement is temporarily stored File Class __exit__ Method

    2. And then it calls File Class __enter__ Method

    3. __enter__ Method to open the file and return to with sentence

    4. The open file handle is passed to opened_file Parameters

    5. We use .write() To write a file

    6. with Statement before calling __exit__ Method

    7. __exit__ Method closes the file


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved