Explain Python class method chaining

PythonServer Side ProgrammingProgramming

Method Chaining

Method chaining is a technique that is used for making multiple method calls on the same object, using the object reference just once. Example −

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

We create an instance of the class Foo −

foo = Foo()

Without method chaining, to call both bar and baz, on the object foo, we do this −

foo.bar()
foo.baz()

With method chaining, we do this −

Chain calls to both methods bar() and baz() on object foo.

foo.bar().baz()

Example

Simple method chaining can be implemented easily 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)

Output

Here is the output of running the above program −

Foo.bar called
Foo.baz called
id(foo): 87108128
id(foo2): 87108128
raja
Published on 23-Jan-2018 15:22:45
Advertisements