Code Explanation:
1. Defining the Class
class Engine:
A class named Engine is defined.
2. Defining the Method start
def start(self):
self.start = "running"
return "init"
This method does two important things:
Creates an instance attribute named start
self.start = "running"
This overwrites the method name on the instance.
After this line, start on the object is no longer a method.
Returns a string
return "init"
3. Creating an Object
e = Engine()
An instance e of class Engine is created.
At this point:
e.start → method (from class)
4. First Call: e.start()
e.start()
Step-by-step:
Python finds start on the class.
Calls the method.
Inside the method:
self.start = "running" creates an instance attribute
The instance attribute shadows the method.
The method returns "init".
Result of first call:
"init"
5. Second Access: e.start
e.start
Python looks for start on the instance.
Finds the instance attribute:
e.start == "running"
The method on the class is no longer used.
6. Printing Both Values
print(e.start(), e.start)
First e.start() → "init"
Second e.start → "running"
7. Final Output
init running
Final Answer
✔ Output:
init running

0 Comments:
Post a Comment