Chaining and Concatenating Python Class Methods

Python Methods and Functions

Combining Methods &it is a method that is used to make multiple method calls on the same object using an object reference only once. Example:

Suppose we have a Foo class that has two methods, bar and baz.

We create an instance of the Foo class:



 foo = Foo () 

No method chaining to call and bar, and baz, for the foo object, we do this:



 foo.bar () foo.baz () 

With method chaining we do this:

Chaining both the bar () and baz () methods for foo.

 foo.bar (). baz () 

Simple method chaining can be easily implemented in Python.

 class Foo (object): def bar (self): print "Foo.bar called" return self def baz (self): print "Foo.baz called" return self foo = Foo () foo2 = foo.bar (). baz () print "id (foo):", id (foo) print "id (foo2 ): ", id (foo2) 

Here is the result of running the above program:

 Foo.bar called Foo.baz called id (foo): 87108128 id (foo2): 87108128 







Get Solution for free from DataCamp guru