Code Explanation:
1. Defining the Class
class Chain:
A new class named Chain is defined.
It will contain a method that supports method chaining.
2. Defining the step() Method
def step(self):
print("Step", end="")
return self
Breakdown:
step() prints the word "Step"
end="" prevents a newline → printing happens continuously.
return self is the critical part:
It returns the same object
This allows calling another method on the same line.
In short:
Returning self allows multiple method calls one after another.
This is called method chaining.
3. Creating an Object
c = Chain()
An object c of class Chain is created.
4. Method Chaining in Action
c.step().step().step()
Step-by-step execution:
c.step()
prints: Step
returns c
(returned object).step()
again prints: Step
again returns c
(returned object).step()
prints final: Step
Each call prints "Step" and returns the same object again.
5. Final Output
All three prints combine into:
StepStepStep
Final Answer
Output:
StepStepStep


0 Comments:
Post a Comment