Code Explanation:
๐น 1️⃣ Defining Class A
class A:
Creates a class named A.
Objects created from this class will inherit its methods and attributes.
๐น 2️⃣ Defining the __getattr__ Method
def __getattr__(self, name):
return name.upper()
This method is automatically called when Python cannot find an attribute normally.
Parameters:
self → the object
name → the attribute name being accessed
Behavior here:
It converts the attribute name to uppercase and returns it.
Example:
a.test → "TEST"
๐น 3️⃣ Creating an Object
a = A()
Creates an instance named a.
At this moment:
a.__dict__ = {}
The object has no attributes defined.
๐น 4️⃣ Accessing Missing Attributes
print(a.test + a.python)
Python evaluates each attribute separately.
๐น Step 1: Accessing a.test
Python lookup order:
1️⃣ Check instance dictionary
a.__dict__
No test found.
2️⃣ Check class attributes
A.__dict__
No test.
3️⃣ Check parent classes
Still not found.
4️⃣ Python calls:
__getattr__(a, "test")
Inside the method:
return "TEST"
So:
a.test → "TEST"
๐น Step 2: Accessing a.python
Again Python cannot find the attribute.
So it calls:
__getattr__(a, "python")
Inside the method:
return "PYTHON"
So:
a.python → "PYTHON"
๐น Step 3: String Concatenation
"TEST" + "PYTHON"
Result:
"TESTPYTHON"
✅ Final Output
TESTPYTHON

0 Comments:
Post a Comment