Code Explanation:
1. Class Definition
class P:
Defines a class P, which will contain an initializer and a private variable.
2. Constructor of Class P
def __init__(self):
Defines the constructor that runs when a P object is created.
self.__v = 11
Creates a private attribute named __v and sets it to 11.
Because it starts with double underscore, Python name-mangles it to _P__v.
3. Child Class Definition
class Q(P):
Defines class Q that inherits from class P.
So Q objects automatically get all attributes and methods of P.
4. Method in Class Q
def check(self):
Defines a method inside class Q.
return hasattr(self, "__v")
The hasattr function checks whether the object has an attribute named "__v".
But due to name mangling, the actual attribute name in the object is _P__v,
NOT __v.
So this check returns False.
5. Creating an Object
q = Q()
Creates an instance of class Q.
Since Q inherits from P, the constructor of P runs → _P__v is created.
6. Printing the Result
print(q.check())
Calls check(), which checks if the object has an attribute named "__v".
It doesn’t (because it's stored as _P__v).
So it prints:
False
Output:
False


0 Comments:
Post a Comment