Code Explanation:
1. Defining the Class
class Lock:
A class named Lock is created.
This class will be used as a context manager.
A context manager is an object that defines what should happen:
when entering a with block (__enter__)
when exiting a with block (__exit__)
2. Defining the __enter__ Method
def __enter__(self):
print("Start")
__enter__ is automatically called when execution enters the with block.
Here, it simply prints "Start".
3. Defining the __exit__ Method
def __exit__(self, a, b, c):
print("End")
__exit__ is automatically called when execution leaves the with block.
It runs whether:
the block finishes normally, or
an exception occurs.
The parameters a, b, and c are for exception details (type, value, traceback).
4. Using the Class with with
with Lock():
What happens internally:
Python creates a Lock() object.
Calls its __enter__() method → prints "Start".
Then executes the code inside the with block.
5. The Body of the with Block
pass
pass means do nothing.
No output occurs here.
6. Exiting the with Block
After pass executes:
Python calls __exit__() automatically.
__exit__() prints "End".
7. Final Output
Start
End


0 Comments:
Post a Comment