Code Explanation:
1. Class Definition
class Lock:
Explanation:
A class named Lock is created.
This class will represent an object that has a private value (key).
2. Constructor Method (__init__)
def __init__(self):
Explanation:
__init__ is a constructor.
It runs automatically when an object of the class is created.
self refers to the current object.
3. Private Instance Variable
self.__key = 123
Explanation:
__key is a private instance variable.
Because it starts with double underscore (__), Python applies name mangling.
Internally, Python renames it as:
_Lock__key
This prevents accidental access from outside the class.
4. Object Creation
l = Lock()
Explanation:
An object l of class Lock is created.
During object creation, the constructor runs and:
self.__key = 123 is stored internally as _Lock__key.
5. Accessing Private Variable Using Name Mangling
print(l._Lock__key)
Explanation:
Direct access like l.__key is not allowed.
But Python allows access using name-mangled form:
_ClassName__variableName
Here:
_Lock__key
So the value 123 is printed.
FINAL OUTPUT
123


0 Comments:
Post a Comment