Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Method chaining can be invoked programmatically in Python by calling methods one after another on the same object, returning the modified object at each step. For example:

class MyClass:
    def __init__(self, x):
        self.x = x

    def add(self, y):
        self.x += y
        return self

    def subtract(self, z):
        self.x -= z
        return self

# Chaining example
myobject = MyClass(10)
myobject.add(5).subtract(3)
print(myobject.x)  # Output: 12

In this example, the add() method adds a value to the x attribute of the MyClass instance and then returns itself, allowing for method chaining. The subtract() method does the same but subtracts the value. To invoke method chaining programmatically, simply call the methods one after another on the same object as shown in the example.