Context managers का उपयोग

Python में Functions लिखना

Shayne Miel

Software Architect @ Duo Security

Context manager क्या है?

एक context manager:

  • एक संदर्भ सेट करता है
  • आपका कोड चलाता है
  • संदर्भ हटा देता है
Python में Functions लिखना

कैटरिंग वाली पार्टी

खाली कमरा

Python में Functions लिखना

कैटरिंग वाली पार्टी

कैटरिंग लगा कमरा

Python में Functions लिखना

कैटरिंग वाली पार्टी

पार्टी चल रहा कमरा

Python में Functions लिखना

कैटरिंग वाली पार्टी

कैटरिंग लगा कमरा

Python में Functions लिखना

कैटरिंग वाली पार्टी

खाली कमरा

Python में Functions लिखना

Context के रूप में कैटरिंग पार्टी

Context managers:

  • एक संदर्भ सेट करते हैं
  • आपका कोड चलाते हैं
  • संदर्भ हटा देते हैं

Caterers:

  • खाने-पीने के साथ टेबल लगाते हैं
  • आपको और दोस्तों को पार्टी करने देते हैं
  • सफाई करके टेबल हटा देते हैं
Python में Functions लिखना

वास्तविक दुनिया का उदाहरण

with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))

open() तीन काम करता है:

  • फ़ाइल खोलकर संदर्भ सेट करता है
  • उस फ़ाइल पर आपका कोई भी कोड चलाने देता है
  • फ़ाइल बंद करके संदर्भ हटा देता है
Python में Functions लिखना

Context manager का उपयोग

with
Python में Functions लिखना

Context manager का उपयोग

with <context-manager>()
Python में Functions लिखना

Context manager का उपयोग

with <context-manager>(<args>)
Python में Functions लिखना

Context manager का उपयोग

with <context-manager>(<args>):
Python में Functions लिखना

Context manager का उपयोग

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"
Python में Functions लिखना

Context manager का उपयोग

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
Python में Functions लिखना

Context manager का उपयोग

with <context-manager>(<args>) as <variable-name>:
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))
Python में Functions लिखना

अभ्यास करते हैं!

Python में Functions लिखना

Preparing Video For Download...