Skip to content

Instantly share code, notes, and snippets.

@nasutionam
Forked from bagrow/method_chaining.py
Created November 16, 2018 08:28
Show Gist options
  • Save nasutionam/6ac8e0184fc9a650bf428fcb5ab90b1c to your computer and use it in GitHub Desktop.
Save nasutionam/6ac8e0184fc9a650bf428fcb5ab90b1c to your computer and use it in GitHub Desktop.

Revisions

  1. @bagrow bagrow revised this gist Dec 6, 2016. 1 changed file with 13 additions and 15 deletions.
    28 changes: 13 additions & 15 deletions method_chaining.py
    Original file line number Diff line number Diff line change
    @@ -34,18 +34,16 @@ def train_prod(self, beta):
    return self


    if __name__ == "__main__":

    # initialize the object:
    jv = Jarvis([1,2,3,4])

    # use its methods
    jv.train_sum(2)
    jv.train_prod(10)
    print(jv.data)


    # the same thing with method chaining:
    jv = Jarvis([1,2,3,4])

    print(jv.train_sum(2).train_prod(10).data)
    # initialize the object:
    jv = Jarvis([1,2,3,4])

    # use its methods
    jv.train_sum(2)
    jv.train_prod(10)
    print(jv.data)


    # the same thing with method chaining:
    jv = Jarvis([1,2,3,4])

    print(jv.train_sum(2).train_prod(10).data)
  2. @bagrow bagrow created this gist Dec 6, 2016.
    51 changes: 51 additions & 0 deletions method_chaining.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    # method_chaining.py
    # Jim Bagrow
    # Last Modified: 2016-12-05

    """
    Method chaining (or cascading) is a technique for making many calls to an
    object with less code. Each method should return a reference to the object
    itself (in Python this reference is called `self`). Then, instead of writing:
    A.method1()
    A.method2()
    You can write:
    A.method1().method2()
    This works because A.method1(), while it may perform some internal task,
    returns A itself. So, in a sense, A.method1() is equal to A.
    Below is a silly Python example.
    """

    class Jarvis():

    def __init__(self, data):
    self.data = data

    def train_sum(self, newX):
    self.data = [x + newX for x in self.data]

    return self # This is what allows chaining

    def train_prod(self, beta):
    self.data = [x*beta for x in self.data]
    return self


    if __name__ == "__main__":

    # initialize the object:
    jv = Jarvis([1,2,3,4])

    # use its methods
    jv.train_sum(2)
    jv.train_prod(10)
    print(jv.data)


    # the same thing with method chaining:
    jv = Jarvis([1,2,3,4])

    print(jv.train_sum(2).train_prod(10).data)