Code Explanation:
1. Defining the class
class Box:
This line defines a new class named Box.
A class is a blueprint for creating objects.
2. Class attribute
x = 5
x is a class variable.
It belongs to the class Box, and every object of Box can access it.
Its value is 5.
3. Special method __getattr__
def __getattr__(self, name):
return 99
__getattr__ is a special (magic) method in Python.
It is called only when an attribute is NOT found normally.
Parameters:
self → the current object
name → the name of the attribute being accessed
This method always returns 99, no matter which missing attribute is requested.
4. Creating an object
b = Box()
This creates an instance (object) of the Box class.
b now refers to that object.
5. Printing attributes
print(b.x, b.y)
Let’s break this into two parts:
๐น b.x
Python looks for x in:
The object b
The class Box
x exists in the class and its value is 5
So b.x → 5
๐น b.y
Python looks for y in:
The object b
The class Box
y does not exist
Python then calls:
__getattr__(self, "y")
__getattr__ returns 99
So b.y → 99
✅ Final Output
5 99

0 Comments:
Post a Comment