Code Explanation:
1. Defining the Class
class Player:
def play(self):
return "playing"
A class named Player is defined.
It has a method play() that returns the string "playing".
At this point:
Player.play → method
2. Creating an Instance
p = Player()
An object p of class Player is created.
Initially, p does not have its own play attribute.
Method lookup would normally find play on the class.
3. Assigning a New Attribute on the Instance
p.play = lambda: "paused"
This line creates an instance attribute named play.
The instance attribute shadows (overrides) the class method.
Now:
p.__dict__["play"] → lambda: "paused"
Important:
Instance attributes have higher priority than class attributes during lookup.
4. Calling p.play()
print(p.play())
Step-by-step:
Python looks for play on the instance p.
Finds the instance attribute (lambda: "paused").
Calls the lambda.
Returns "paused".
5. Final Output
paused
Final Answer
✔ Output:
paused

0 Comments:
Post a Comment