Explanation:
1. ๐️ Define the Class
class A:
This creates a class named A.
We will later create an object from this class.
2. ๐ Create a Class Attribute
x = 10
Here, x is a class attribute.
Every object of A can access it unless an instance attribute with the same name overrides it.
So:
a.x
can find the value:
10
3. ๐ Define __getattr__()
def __getattr__(self, name):
__getattr__() is a special method that Python calls when an attribute cannot be found normally.
The name parameter receives the name of the missing attribute.
For example:
a.y
doesn't find y, so Python effectively calls:
a.__getattr__("y")
4. ๐ฏ Return a Default Value
return 99
Whenever an attribute is missing, this method returns 99.
So:
a.y
becomes:
99
Notice that __getattr__() does not run for attributes that already exist.
5. ๐ Create an Object
a = A()
An object a is created from class A.
At this point, a can access the class attribute:
a.x → 10
6. ๐จ️ Access a.x
print(a.x, a.y)
First Python evaluates:
a.x
x exists in class A.
Therefore, Python gets:
a.x → 10
__getattr__() is not called.
7. ⚠️ Access a.y
Python then evaluates:
a.y
There is no y attribute in the instance or class.
So Python calls:
__getattr__(a, "y")
The method returns:
99
Therefore:
a.y → 99
๐ Internal Flow
a.x
↓
Found normally
↓
10
But:
a.y
↓
Not found
↓
__getattr__("y")
↓
99
๐ง __getattr__() vs __getattribute__()
Method When called?
__getattribute__() For every attribute access
__getattr__() Only when normal lookup fails
๐ก Interview Trick
The biggest point to remember:
__getattr__() is a fallback mechanism for missing attributes.
So the final result is:
✅ Output
10 99

0 Comments:
Post a Comment