Code Explanation
1. Defining the Class
class Tool:
A class named Tool is defined.
2. Defining Method run
def run(self):
return "old"
A method named run is created.
If called normally:
Tool().run() → "old"
At this moment:
Tool.run → original method
3. Creating an Object
t = Tool()
An instance t of class Tool is created.
Important:
The object does NOT store the method inside itself.
It looks up methods dynamically from the class.
4. Modifying the Class at Runtime
Tool.run = lambda self: "new"
The class method run is replaced.
Now:
Tool.run → new lambda function
This change affects:
All future objects
All existing objects
Because method lookup happens at call time, not at object creation time.
5. Calling the Method
print(t.run())
Step-by-step:
Python looks for run in t.__dict__ → ❌ not found.
Looks in class Tool.
Finds the new lambda function.
Executes it.
Returns "new".
6. Final Output
new
✅ Final Answer
✔ Output:
new
400 Days Python Coding Challenges with Explanation

0 Comments:
Post a Comment