Explain Python class method chaining

In object-oriented programming, method chaining is a programming technique where multiple method calls are linked together in a single expression. Each method returns an object (typically self), allowing the next method to be called on the result.

Method chaining provides two key benefits ?

  • Reduced code length − No need to create intermediate variables for each step

  • Improved readability − Operations flow sequentially in a clear, logical order

How Method Chaining Works

For method chaining to work, each method must return an object (usually self) so the next method can be called on it. Here's a basic example ?

class Calculator:
    def __init__(self):
        self.value = 0
    
    def add(self, num):
        self.value += num
        print(f"Added {num}, value is now {self.value}")
        return self  # Return self to enable chaining
    
    def multiply(self, num):
        self.value *= num
        print(f"Multiplied by {num}, value is now {self.value}")
        return self
    
    def subtract(self, num):
        self.value -= num
        print(f"Subtracted {num}, value is now {self.value}")
        return self

# Method chaining in action
calc = Calculator()
result = calc.add(10).multiply(3).subtract(5)
print(f"Final value: {result.value}")
Added 10, value is now 10
Multiplied by 3, value is now 30
Subtracted 5, value is now 25
Final value: 25

Chaining Built-in Methods

Python's built-in methods often return objects that support chaining. Here's an example with string methods ?

days_of_week = "Monday Tuesday Wednesday Thursday Friday Saturday,Sunday"
weekend_days = days_of_week.split()[-1].split(',')
print(weekend_days)
['Saturday', 'Sunday']

Method Chaining with Pandas

Pandas DataFrames support extensive method chaining for data manipulation. Here's a practical example ?

import pandas as pd

# Create sample data
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
    'Age': [25, 30, 35, 28],
    'Marks': [85, 92, 78, 88],
    'Gender': ['F', 'M', 'M', 'F']
}

df = pd.DataFrame(data)

# Method chaining example
result = (df
    .assign(Percentage=lambda x: (x['Marks'] * 100) / 100)  # Add percentage column
    .drop(columns=['Gender'])  # Remove gender column
    .sort_values('Marks', ascending=False)  # Sort by marks
    .head(3))  # Get top 3

print(result)
      Name  Age  Marks  Percentage
1      Bob   30     92        92.0
3    Diana   28     88        88.0
0    Alice   25     85        85.0

Method Chaining with NumPy

NumPy arrays also support method chaining for array operations ?

import numpy as np

# Chaining NumPy methods
chained_array = np.arange(1, 32, 2).reshape(4, 4).clip(9, 25)
print(chained_array)
[[ 9  9  9  9]
 [ 9 11 13 15]
 [17 19 21 23]
 [25 25 25 25]]

Best Practices

When implementing method chaining, follow these guidelines ?

  • Always return self − Each method should return the object instance

  • Use parentheses − Wrap long chains in parentheses for better readability

  • One method per line − Break long chains across multiple lines

  • Maintain immutability − Consider returning new objects instead of modifying existing ones

Conclusion

Method chaining is a powerful technique that makes code more concise and readable by linking operations together. It's widely used in popular libraries like Pandas and NumPy, and you can implement it in your own classes by ensuring methods return self.

---
Updated on: 2026-03-24T19:47:26+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements