Code Explanation:
1. Defining Class R
class R:
You begin by creating a class named R, which will have an initializer and a private attribute.
2. Constructor of Class R
def __init__(self):
self.__v = 10
__init__ runs automatically when an object of R (or its child class) is created.
self.__v is a private attribute because it starts with double underscore __.
Python performs name-mangling, converting __v into _R__v internally.
This means subclasses cannot directly access __v using the name __v.
3. Defining Class S that Inherits R
class S(R):
Class S is a child class of R.
It inherits the constructor of class R, so __v is still created inside objects of class S (but as _R__v).
4. Method show() Inside Class S
def show(self):
return hasattr(self, "__v")
The method checks: Does the object have an attribute named "__v"?
Because of name-mangling, the actual attribute name is _R__v, not __v.
So hasattr(self, "__v") will return False.
5. Creating an Object of S and Calling show()
print(S().show())
An object of S is created → this also runs R’s constructor → _R__v is created.
Now show() is called.
hasattr(self, "__v") checks for "__v" exactly.
Since "__v" does not exist (only _R__v does), the result is:
False
Final Output: False


0 Comments:
Post a Comment