Code Explanation:
1️⃣ Defining Class A
class A:
Creates a class named A.
All objects created from this class will use its attributes and methods.
๐น 2️⃣ Defining a Class Attribute
x = 10
x is a class variable.
It belongs to the class A, not to individual objects.
Any instance can access it unless overridden.
So internally:
A.x = 10
๐น 3️⃣ Defining __getattr__
def __getattr__(self, name):
return 99
This method is called only when an attribute is NOT found normally.
Parameters:
self → the object
name → name of the missing attribute
Behavior here:
If an attribute does not exist, return 99.
Example:
a.unknown → 99
๐น 4️⃣ Creating an Object
a = A()
Creates an instance a of class A.
Internally:
a.__dict__ = {}
The object has no instance attributes yet.
๐น 5️⃣ Printing Two Attributes
print(a.x, a.y)
Python evaluates both attributes separately.
๐น Step 1: Accessing a.x
Python follows attribute lookup order:
1️⃣ Check instance dictionary
a.__dict__
No x found.
2️⃣ Check class attributes
A.x
Found:
10
So Python returns 10.
๐ __getattr__ is NOT called because the attribute exists.
๐น Step 2: Accessing a.y
Now Python looks for y.
1️⃣ Instance dictionary
❌ Not found
2️⃣ Class dictionary
❌ Not found
3️⃣ Parent classes (MRO)
❌ Not found
Now Python calls:
__getattr__(self, "y")
Inside the method:
return 99
So the result is 99.
✅ Final Output
10 99

0 Comments:
Post a Comment