216. Method Chaining with Self-Returning Methods
🔹 1. Basic Method Chaining
class User:
def __init__(self, name):
self.name = name
self.email = None
def set_email(self, email):
self.email = email
return self # Returning self enables chaining
def display(self):
print(f"User: {self.name}, Email: {self.email}")
return self # Returning self allows further chaining
user = User("Alice").set_email("alice@example.com").display()🔍 Key Takeaway:
Each method returns
self, allowing multiple calls in one line.
🔹 2. Chaining Methods for a Fluent API
class FluentMath:
def __init__(self, value=0):
self.value = value
def add(self, x):
self.value += x
return self
def subtract(self, x):
self.value -= x
return self
def multiply(self, x):
self.value *= x
return self
def result(self):
print(f"Result: {self.value}")
return self
math = FluentMath().add(10).subtract(3).multiply(2).result()🔍 Key Takeaway:
This pattern is common in mathematical operations or data transformations.
🔹 3. Using Method Chaining in a Configuration Builder
🔍 Key Takeaway:
Used for builder patterns, where configuration is set dynamically.
🔹 4. Method Chaining for String Processing
🔍 Key Takeaway:
Useful in text processing, making transformations clearer.
🔹 5. Chaining for Logging System
🔍 Key Takeaway:
Logging chains make debugging simpler and cleaner.
🔹 6. Method Chaining for HTTP Requests (Mock Example)
🔍 Key Takeaway:
Mimics real-world APIs like Requests, improving readability.
🔹 7. Chaining in File Operations
🔍 Key Takeaway:
Fluent API for file handling can simplify file writing.
🔹 8. Using Method Chaining in a Fluent Query Builder
🔍 Key Takeaway:
Chained SQL queries improve readability.
🔹 9. Chaining in Data Pipelines
🔍 Key Takeaway:
Useful for data transformations.
🔹 10. Chaining with Decorators
🔍 Key Takeaway:
Combining method chaining with decorators for user-friendly creation.
🚀 Summary: When to Use Method Chaining?
Use Case
Example
Configuration Builders
Config().set("key", "value").set("debug", True).show()
Data Processing Pipelines
DataPipeline(data).filter(condition).sort().display()
String Transformations
StringProcessor("text").to_upper().replace("old", "new").show()
Logging Systems
Logger().log("Step 1").log("Step 2").show()
SQL Query Builders
QueryBuilder().where("id=1").order_by("name").execute()
HTTP Requests
Request().set_url("api.com").set_method("POST").send()
Last updated