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 chaining
1class Builder:
# Initialize with empty parts list
2 def __init__(self):
# List to store added parts
3 self.parts = []
# Add a part and return self for chaining
4 def add(self, part):
# Append part to the list
5 self.parts.append(part)
# Return self to enable chaining
6 return self
# Build final result from parts
7 def build(self):
# Join all parts with hyphen
8 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-C
11print(result)

Output

A-B-C
Practice typing this code

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

More Python examples at level 4

← Python typing practice