216. Method Chaining with Self-Returning Methods
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()🔹 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()🔹 3. Using Method Chaining in a Configuration Builder
🔹 4. Method Chaining for String Processing
🔹 5. Chaining for Logging System
🔹 6. Method Chaining for HTTP Requests (Mock Example)
🔹 7. Chaining in File Operations
🔹 8. Using Method Chaining in a Fluent Query Builder
🔹 9. Chaining in Data Pipelines
🔹 10. Chaining with Decorators
🚀 Summary: When to Use Method Chaining?
Last updated