CoursesGalaxy Courses Subscription Knowledge Hub
Knowledge Hub
Design Patterns


Method Chaining In Python

Method chaining is calling methods of object in chained way.

What is Method Chaining?

We can call methods of object in chained way one after another in same line of code using dot operator. That is called method chaining. It can be done by returning self in every method of object, so that when first method is called then it returns object itself, so that second method is called and so on.

This avoids use of some variables, the code can be written in single line and makes code more readable and understandable.

Let's see this example.

sysObj.Configure().DisplayInformation().DoOperation("Backup");

Here we are calling the methods of object sysObj. First we are calling the method Configure(), then the method DisplayInformation() and then the method DoOperation(). When we call the method sysObj.Configuration() then it returns the sysObj object itself, so that we can call the method DisplayInformation() which returns the sysObj object, so that we can call the method DoOperation().

If we don't use the method chaining then we have to write the code in multiple lines.

sysObj.Configure();
sysObj.DisplayInformation();
sysObj.DoOperation("Backup");


Implementation

methodchaining.py




Output

Creating Project .... IntellegentDesigner
Adding File .... ClassDesign.cpp
Adding File .... ObjectDesign.cpp
Building Project .... IntellegentDesigner
Executing .... IntellegentDesigner



Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth", "Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of multiple products. This article is from his course on Advanced JavaScript.







Yearly Subscription


Advanced Python


Data Structures in Python


Design Patterns Through Python

Explore

Courses

Subscription

Knowledge Hub

Design Patterns

Tech Articles

About Us

Overview

Contact Us

CourseGalaxy

CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap between education and industry and provide the training on specific problems of industry to enhance the skills of Engineers in industry to do their job appropriately.

Learn From Us

2018 CourseGalaxy