Guest User

Untitled

a guest
Nov 16th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # method_chaining.py
  5. # Jim Bagrow
  6. # Last Modified: 2016-12-05
  7.  
  8. """
  9. Method chaining (or cascading) is a technique for making many calls to an
  10. object with less code. Each method should return a reference to the object
  11. itself (in Python this reference is called `self`). Then, instead of writing:
  12. A.method1()
  13. A.method2()
  14. You can write:
  15. A.method1().method2()
  16. This works because A.method1(), while it may perform some internal task,
  17. returns A itself. So, in a sense, A.method1() is equal to A.
  18.  
  19. Below is a silly Python example.
  20. """
  21.  
  22. class Jarvis():
  23.  
  24. def __init__(self, data):
  25. self.data = data
  26.  
  27. def train_sum(self, newX):
  28. self.data = [x + newX for x in self.data]
  29.  
  30. return self # This is what allows chaining
  31.  
  32. def train_prod(self, beta):
  33. self.data = [x*beta for x in self.data]
  34. return self
  35.  
  36.  
  37. # initialize the object:
  38. jv = Jarvis([1,2,3,4])
  39.  
  40. # use its methods
  41. jv.train_sum(2)
  42. jv.train_prod(10)
  43. print(jv.data)
  44.  
  45.  
  46. # the same thing with method chaining:
  47. jv = Jarvis([1,2,3,4])
  48.  
  49. print(jv.train_sum(2).train_prod(10).data)
Add Comment
Please, Sign In to add comment