Method Chaining in Python
Level 4221 keystrokes
This implements method chaining by returning self from methods. Each method returns the object allowing continuous calls.
Python code
# Define a builder class for method chaining1class Builder: # Initialize with empty parts list2 def __init__(self): # List to store added parts3 self.parts = [] # Add a part and return self for chaining4 def add(self, part): # Append part to the list5 self.parts.append(part) # Return self to enable chaining6 return self # Build final result from parts7 def build(self): # Join all parts with hyphen8 return "-".join(self.parts)9 # Chain multiple add() calls then build()10result = Builder().add("A").add("B").add("C").build()# Print the result: A-B-C11print(result)Output
A-B-C
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 11)× 11.× 9"× 8_× 4:× 4=× 2-× 1,× 1[× 1