Explain Python class method chaining

PythonServer Side ProgrammingProgramming

In OOP languages methods are a piece of code that can perform a specific task to produce a desired output. Methods are created inside classes and are invoked or called by objects of the class.

Methods are extremely useful in programming as they provide modularity to code by breaking a complex code into manageable blocks. Methods can function independently of other methods, thus making it easy to check individual functionality within a program.

Method chaining in Python

Methods chaining is a style of programming in which invoking multiple method calls occurs sequentially. It removes the pain of assigning variables at each intermediate step as each call performs action on same object and then returns the object to next call.

Method chaining has two useful benefits −

  • It can reduce the length of the overall code as countless variables do not have to be created.

  • It can increase the readability of the code since methods are invoked sequentially.

Example

In this simple example of method chaining in Python, different CalculatorFunctions contains multiple methods which need to be invoked by calculator object. Instead of invoking one after the other, all the functions are chained and invoked in a single line.

In order for method chaining to work, every method must return an object of the class, which in this case is self.

class CalculatorFunctions(): def sum(self): print("Sum called") return self def difference(self): print("Difference called") return self def product(self): print("Product called") return self def quotient(self): print("Quotient called") return self if __name__ == "__main__": calculator = CalculatorFunctions() # Chaining all methods of CalculatorFunctions calculator.sum().difference().product().quotient()

Output

Following is an output of the above code −

Sum called 
Difference called 
Product called 
Quotient called

Example

In this example of chaining built-in methods in python, the days are first split by space, then the last element (Saturday,Sunday) is split by comma to output them as separate entities.

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

Output

Following is an output of the above code −

['Saturday', 'Sunday']

Method Chaining Using Pandas

Pandas is a python package used for solving complex problems in fields of data science and machine learning. The pandas package has many built-in methods that can be chained together to reduce code length.

Example

chaining pandas methods

In this example a csv file is first read and assigned to a data frame. After that different methods of pandas are chained together to manipulate the CSV file.

The .assign() method creates Percentage column, .drop deletes an Gender column, .sort_value sorts the data based on Percentage and .head gives the top three results from the CSV file.

import pandas as pd data_frame = pd.read_csv('E:/Marks.csv', index_col = 0) # Chaining different methods of pandas chained_data_frame = (data_frame.assign(Percentage = (data_frame['Marks']*100)/70) .drop(columns = 'Gender') .sort_values('Percentage', ascending = False) .head(3)) print(chained_data_frame)

Output

Following is an output of the above code −

      Age   Marks    Percentage
ID
4     40    68       97.142857
2     20    65       92.857143
3     30    60       85.714286

Method Chaining Using NumPy

NumPy is a python package that provides support for multidimensional array objects and multiple routines to perform extremely fast operations on arrays. Just like pandas methods, NumPy methods can also be chained.

Example

chaining NumPy methods

In this example different NumPy methods are chained to create a 4x4 matrix. The .arange() method creates a matrix from 1 to 32 with step count of 2, .reshape adjusts the matrix into a 4x4 configuration and .clip is used to set minimum element to 9 and maximum to 25 in the matrix.

import numpy as np # Chaining different methods of numpy chained_numpy = np.arange(1, 32, 2).reshape(4, 4).clip(9, 25) print(chained_numpy)

Output

Following is an output of the above code

[[ 9  9  9  9]
 [ 9 11 13 15]
 [17 19 21 23]
 [25 25 25 25]]
raja
Updated on 23-Nov-2022 08:10:56

Advertisements