Code Explanation:
1. Class P definition
class P:
Declares a new class named P.
P will act as a base (parent) class for other classes.
2. __init__ constructor in P
def __init__(self):
self.__v = 12
Defines the constructor that runs when a P (or subclass) instance is created.
self.__v = 12 creates an attribute named __v on the instance.
Because the name starts with two underscores, Python will name-mangle this attribute to _P__v internally to make it harder to access from outside the class (a form of limited privacy).
3. Class Q definition inheriting from P
class Q(P):
Declares class Q that inherits from P.
Q gets P’s behavior (including __init__) unless overridden.
4. check method in Q
def check(self):
return hasattr(self, "__v")
Defines a method check() on Q that tests whether the instance has an attribute literally named "__v" (not the mangled name).
hasattr(self, "__v") looks for an attribute with the exact name __v on the instance — it does not account for name mangling.
5. Create an instance of Q
q = Q()
Instantiates Q. Because Q inherits P, P.__init__ runs and sets the instance attribute — but under the mangled name _P__v, not __v.
6. Print the result of q.check()
print(q.check())
Calls check() which runs hasattr(self, "__v").
The instance does not have an attribute literally named __v (it has _P__v), so hasattr returns False.
The printed output is:
False
Final Output:
False


0 Comments:
Post a Comment