Code Explanation:
1. Defining the Class
class Service:
A class named Service is defined.
2. Defining a Class Attribute
status = "ok"
status is a class attribute.
Normally, Service().status would return "ok".
3. Overriding __getattribute__
def __getattribute__(self, name):
__getattribute__ is a special method that is called for every attribute access on an instance.
It intercepts all attribute lookups.
4. Checking the Attribute Name
if name == "status":
return "overridden"
If the requested attribute is "status", the method returns "overridden" instead of the actual value.
5. Default Attribute Lookup for Others
return super().__getattribute__(name)
For any attribute other than "status", it delegates the lookup to Python’s normal mechanism.
6. Creating an Instance and Accessing status
print(Service().status)
Step-by-step:
Service() creates a new instance.
.status is accessed on that instance.
Python calls __getattribute__(self, "status").
The method checks name == "status" → True.
Returns "overridden".
print prints "overridden".
7. Final Output
overridden
Final Answer
✔ Output:
overridden


0 Comments:
Post a Comment