Course contentsShow
← Python
Lesson 475 of 1,0607. Object-Oriented ProgrammingFree lesson

Building Fluent Interfaces with Method Chaining

Design methods that return self to enable readable, chained syntax for complex object configuration and state updates.

Building Fluent Interfaces with Method Chaining

In this lesson, you will learn how to design objects that support "fluent interfaces," allowing you to chain multiple method calls together in a single, highly readable line of code.

The Problem: Verbosity

Typically, when we configure an object, we write several lines of code, repeating the object's variable name each time:

builder = UserBuilder()
builder.set_name("Alice")
builder.set_age(30)
builder.set_role("Admin")

This is functional, but it feels repetitive. A fluent interface turns this into a clean, expressive "chain" of actions.

The Solution: Returning self

The secret to method chaining is simple: instead of having your setter methods return None (the default behavior in Python), you make them return the object instance itself using return self.

By returning the object, the result of the first method call becomes the object we immediately call the next method on.

class UserBuilder:
    def __init__(self):
        self.name = None
        self.age = None

    def set_name(self, name):
        self.name = name
        return self  # Return self to enable chaining

    def set_age(self, age):
        self.age = age
        return self  # Return self to enable chaining

# Now we can chain!
user = UserBuilder().set_name("Alice").set_age(30)

Why Use This?

This pattern is popular in configuration objects, database query builders, and unit testing libraries. It creates a "domain-specific" feel that reads almost like a natural language sentence. Because the method returns the same instance it was called on, you can keep adding methods indefinitely until the object is fully configured.

Note that this works best for methods that perform configuration or state updates. You wouldn't use this for a method that is expected to return a specific piece of data (like a getter or a calculation), as the primary goal of the return value here is to facilitate the chain.

Key Takeaway: By returning self at the end of your methods, you allow users to chain calls together, transforming verbose configuration steps into a concise, readable, and fluent syntax.