OOP __enter__ & __exit__ dunder methods in Python #kody_az
Dərs haqqında
__enter__ və __exit__ Python-da with ifadəsi ilə avtomatik resurs idarəçiliyini təmin edən xüsusi (“dunder”) metodlardır. with some_object: yazdıqda, Python bu iki metoddan istifadə edərək “bloka daxil olarkən resursu qur, blokdan çıxarkən isə onu təmizlə” prinsipini tətbiq edir.
• __enter__
with blokunun başlanğıcında çağırılır. Adətən burada lazımi resurs (məsələn, fayl, verilənlər bazası bağlantısı və ya lock) əldə olunur və hazır vəziyyətə gətirilir. Bu metod, with ... as something: formasında istifadə olunarsa, blok içində istifadə olunacaq obyekti (something) geri qaytara bilər.
• __exit__
with bloku bitəndən sonra çağırılır. İstər normal icra nəticəsində, istərsə də blok daxilində istisna (exception) atılsın, həmişə işə düşür. Burada resurslar təmizlənir və ya azad edilir (fayl bağlanır, verilənlər bazası tranzaksiyası commit/rollback edilir, lock buraxılır və s.). Bu metod, həmçinin istisnaların idarəolunması (məsələn, bəzilərinin yatırılması və ya yenidən atılması) üçün cavabdehdir.
Beləliklə, __enter__ və __exit__ metodları resursların istifadəsi prosesini sadələşdirir və məlumat sızması (resource leak) kimi problemlərin qarşısını alır. Bu, try/finally blokları yazmadan resursları daha səliqəli və etibarlı idarə etməyə kömək
=====
__enter__ and __exit__ are special (“dunder”) methods that enable Python objects to work with the with statement for automatic setup and cleanup. When you write with some_object:, Python looks for these two methods to define the context in which the block of code will run.
• __enter__ is called at the start of the with block. It typically acquires or sets up a resource and can return it for use inside the block. For example, it might open a file, start a database transaction, or acquire a lock.
• __exit__ is called after the with block finishes, whether it finishes normally or an exception was raised. It is responsible for cleaning up or releasing the resource. That might mean closing the file, rolling back or committing the database transaction, or releasing the lock. This method can also handle exceptions that occurred inside the block; if it indicates that the exception was handled, then the exception is suppressed. If not, the exception is re‐raised.
Together, __enter__ and __exit__ provide a clear structure for managing resources safely and consistently, without having to write separate try/finally blocks each time.
#python #kody_az #kodyaz #viral #fleet #jetbrains #pycharm #oop #viralcode #viralvideo #random #code #coder #azerbaycan #azerbaijan #azərbaycan #baku #baki #programming #programmer #codes #hazırlıq #hazirliq #kurs #kurslar #course #courses #online #onlinecourses #test #quiz