Code Explanation:
1. Class Definition
class A:
This defines a class named A.
A class is a blueprint for creating objects.
Any object created from this class will follow its structure.
2. Constructor Method
def __init__(self):
__init__ is the constructor.
It runs automatically when an object is created.
It is used to initialize object data.
3. Private Variable Creation
self.__x = 5
__x is a private variable.
Python performs name mangling, converting:
__x → _A__x
This prevents direct access from outside the class.
The value 5 is safely stored inside the object.
4. Object Creation
a = A()
An object named a is created.
The constructor runs automatically.
Now internally the object contains:
a._A__x = 5
5. Checking Attribute Using hasattr()
print(hasattr(a, "__x"))
hasattr(object, "attribute") checks if the attribute exists.
Since __x was name-mangled to _A__x,
the exact name "__x" does not exist in the object.
So this returns:
False
Final Output
False


0 Comments:
Post a Comment