Code Explanation:
๐น 1️⃣ Defining Class A
class A:
Creates a class named A
Inherits from object by default
๐น 2️⃣ Overriding __getattribute__
def __getattribute__(self, name):
__getattribute__ is a special method
It is called every time ANY attribute is accessed
It intercepts all attribute lookups
⚠ Important:
This runs even before checking:
Instance attributes
Class attributes
Descriptors
MRO
๐น 3️⃣ Custom Condition
if name == "x":
return 100
If someone tries to access attribute "x"
It immediately returns 100
Python will NOT continue normal lookup
This overrides everything.
๐น 4️⃣ Calling Parent for Other Attributes
return super().__getattribute__(name)
For all other attributes, we delegate to the normal lookup mechanism
Prevents infinite recursion
⚠ If we wrote:
return self.__dict__[name]
It could cause recursion issues.
๐น 5️⃣ Creating Object
a = A()
Creates instance a
a.__dict__ is empty initially
๐น 6️⃣ Assigning Instance Attribute
a.x = 5
This does:
Adds 'x': 5 into a.__dict__
So internally:
a.__dict__ = {'x': 5}
๐ Assignment does NOT use __getattribute__
It uses normal attribute setting.
๐น 7️⃣ Accessing a.x
print(a.x)
Here is what happens:
Step-by-step execution:
Python calls:
a.__getattribute__("x")
Inside __getattribute__
name == "x" → True
Immediately returns:
100
It NEVER checks:
a.__dict__
class attributes
MRO
descriptors
✅ Final Output
100

0 Comments:
Post a Comment