- Learning Objectives
- Prerequisites
- Introduction
- What is Method Chaining?
- Why is Method Chaining Required?
- How Method Chaining Works
- Returning self
- Fluent Interface
- Method Chaining vs Constructor Chaining
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Method Chaining.
- Explain why Method Chaining is required.
- Learn how Method Chaining works.
- Understand the importance of returning
self. - Create Fluent Interfaces.
- Differentiate Method Chaining and Constructor Chaining.
Before learning this chapter, you should know:
- Classes
- Objects
- Methods
- Constructors
- Constructor Chaining
- self Keyword
In Object-Oriented Programming,
an object usually contains multiple methods.
Normally,
we call methods one after another.
Example
student.set_name("Rahul")
student.set_age(21)
student.display()Although this works correctly,
it can become lengthy when many methods are involved.
Python provides a cleaner approach called Method Chaining.
Method Chaining allows multiple methods to be called in a single statement.
Method Chaining is the process of calling multiple methods one after another using the same object in a single statement.
This is possible when each method returns the current object using
return selfCalling multiple methods continuously using the same object is called Method Chaining.
Suppose we are creating a Student object.
Without Method Chaining,
we write
student.set_name("Rahul")
student.set_age(21)
student.set_course("Python")
student.display()Using Method Chaining,
the same code becomes
student.set_name("Rahul")\
.set_age(21)\
.set_course("Python")\
.display()This improves readability and makes the code more expressive.
Method Chaining works because every method returns
selfThe returned object immediately calls the next method.
Flow
Method 1
↓
returns self
↓
Method 2
↓
returns self
↓
Method 3
↓
returns self
↓
Next Method
The most important requirement for Method Chaining is
return selfExample
class Student:
def set_name(self, name):
self.name = name
return selfWithout
return selfMethod Chaining is not possible.
A programming style where methods return the current object to allow continuous method calls is called a Fluent Interface.
Many modern frameworks use this design pattern.
Examples include:
- Django ORM
- Pandas
- SQLAlchemy
- PySpark
- Selenium WebDriver
| Method Chaining | Constructor Chaining |
|---|---|
| Calls multiple methods | Calls multiple constructors |
Uses return self |
Uses super() |
| Improves readability | Initializes parent objects |
| Happens after object creation | Happens during object creation |
Consider Online Shopping.
Instead of writing
Select Product
Add to Cart
Apply Coupon
Proceed to Checkout
Make Payment
as separate disconnected actions,
many APIs allow
selectProduct()
↓
addToCart()
↓
applyCoupon()
↓
checkout()
↓
pay()
This resembles Method Chaining.
Object Created
↓
Method Called
↓
Method Returns self
↓
Next Method Called
↓
Method Returns self
↓
Next Method Called
↓
Execution Complete
- Cleaner code.
- Better readability.
- Reduces repeated object references.
- Supports Fluent Interfaces.
- Makes APIs easier to use.
Method Chaining is used in:
- Django ORM
- Pandas
- SQLAlchemy
- Selenium
- PySpark
- Machine Learning Libraries
- REST API Builders
In this part, we learned:
- Method Chaining
- Need for Method Chaining
- Returning
self - Fluent Interface
- Method Chaining vs Constructor Chaining
- Internal Working
Write a Python program to demonstrate Method Chaining.
class Student:
def set_name(self, name):
self.name = name
return self
def set_age(self, age):
self.age = age
return self
def display(self):
print("Name :", self.name)
print("Age :", self.age)
return self
student = Student()
student.set_name("Rahul").set_age(21).display()Name : Rahul
Age : 21
Each method returns
selfTherefore,
the returned object immediately calls the next method.
Write a Python program to demonstrate why return self is required.
class Student:
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
student = Student()
student.set_name("Rahul").set_age(21)AttributeError:
'NoneType' object has no attribute 'set_age'
set_name() returns
NoneTherefore,
Python tries to execute
None.set_age()which produces an error.
class Calculator:
def __init__(self):
self.result = 0
def add(self, value):
self.result += value
return self
def subtract(self, value):
self.result -= value
return self
def multiply(self, value):
self.result *= value
return self
def display(self):
print("Result :", self.result)
return self
calculator = Calculator()
calculator.add(20).subtract(5).multiply(2).display()Result : 30
Execution
0
↓
+20
↓
20
↓
-5
↓
15
↓
×2
↓
30
class Bank:
def deposit(self, amount):
print("Deposited :", amount)
return self
def withdraw(self, amount):
print("Withdrawn :", amount)
return self
def balance(self):
print("Balance Checked")
return self
bank = Bank()
bank.deposit(5000).withdraw(2000).balance()Deposited : 5000
Withdrawn : 2000
Balance Checked
class Student:
def name(self, value):
self.student_name = value
return self
def course(self, value):
self.student_course = value
return self
def marks(self, value):
self.student_marks = value
return self
def display(self):
print(self.student_name)
print(self.student_course)
print(self.student_marks)
return self
Student().name("Rahul").course("Python").marks(95).display()Rahul
Python
95
class Employee:
def set_name(self, name):
self.name = name
return self
def set_salary(self, salary):
self.salary = salary
return self
def show(self):
print(self.name)
print(self.salary)
return self
Employee().set_name("Rahul").set_salary(50000).show()Rahul
50000
class Demo:
def one(self):
print("Method One")
return self
def two(self):
print("Method Two")
return self
def three(self):
print("Method Three")
return self
obj = Demo()
obj.one().two().three()Method One
Method Two
Method Three
Each method returns the same object,
allowing continuous method calls.
class Query:
def select(self):
print("SELECT")
return self
def where(self):
print("WHERE")
return self
def order_by(self):
print("ORDER BY")
return self
Query().select().where().order_by()SELECT
WHERE
ORDER BY
This resembles the Fluent Interface used in many frameworks such as Django ORM and SQLAlchemy.
class Message:
def __init__(self):
self.text = ""
def add(self, word):
self.text += word + " "
return self
def display(self):
print(self.text)
return self
Message().add("Python").add("is").add("Awesome").display()Python is Awesome
class Pizza:
def size(self, value):
print("Size :", value)
return self
def cheese(self):
print("Extra Cheese")
return self
def toppings(self, value):
print("Toppings :", value)
return self
def order(self):
print("Order Confirmed")
return self
Pizza().size("Large").cheese().toppings("Mushroom").order()Size : Large
Extra Cheese
Toppings : Mushroom
Order Confirmed
Builder-style APIs commonly use Method Chaining.
Each method configures the object and returns the same object.
Object Created
↓
Method 1 Called
↓
Returns self
↓
Method 2 Called
↓
Returns self
↓
Method 3 Called
↓
Execution Completed
Student Object
│
▼
+----------------------------+
name
↓
Rahul
age
↓
21
----------------------------
set_name()
set_age()
display()
↓
return self
+----------------------------+
- Improves readability.
- Produces cleaner code.
- Reduces repeated object references.
- Supports Fluent Interfaces.
- Makes APIs intuitive.
- Encourages reusable code.
- Always return
selfif chaining is required. - Keep methods focused on a single task.
- Use meaningful method names.
- Avoid overly long chains that reduce readability.
- Validate input before returning
self.
Forgetting to return self.
def set_name(self, name):
self.name = nameMethod Chaining will fail.
Returning another object instead of self.
If another object is returned,
subsequent methods may not exist.
Performing unrelated operations inside chained methods.
Each method should perform one logical task.
Creating excessively long chains.
Break long chains into multiple statements if readability suffers.
Method Chaining is the technique of calling multiple methods on the same object in a single statement by returning self from each method.
It returns the current object so that the next method can be called immediately.
The method returns None by default, causing the next chained method call to fail with an AttributeError.
A Fluent Interface is a design style where methods return the current object, enabling readable chained method calls.
Method Chaining links multiple method calls using return self.
Constructor Chaining links constructors using super() during object initialization.
- Django ORM
- Pandas
- SQLAlchemy
- Selenium
- PySpark
Yes. It reduces repeated object references and makes related operations appear together.
No. It is a design choice used to improve readability and API usability.
Yes. It only requires methods to return self.
Every chained method must return the current object using:
return self- Create a Calculator using Method Chaining.
- Create a Student class using chained setter methods.
- Create a BankAccount class using Method Chaining.
- Create a Builder-style Pizza class.
- Demonstrate why Method Chaining fails without
return self.
- Method Chaining calls multiple methods in one statement.
- Each method returns
self. return selfis mandatory for chaining.- Method Chaining improves readability.
- Fluent Interfaces are based on Method Chaining.
- Commonly used in Django ORM, Pandas, SQLAlchemy, and Selenium.
In this chapter, you learned:
- Method Chaining
- Returning
self - Fluent Interface
- Method Chaining vs Constructor Chaining
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision