Skip to content

Commit

Permalink
the puprose of the return self idioms in my code examples
Browse files Browse the repository at this point in the history
  • Loading branch information
rasbt committed Mar 3, 2016
1 parent 3eacf85 commit 2cdfee3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions faq/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,5 @@ Sebastian
- [Which book version/format would you recommend?](./version.md)
- [Why did you choose Python for machine learning?](./why-python.md)
- [Why do you use so many leading and trailing underscores in the code examples?](./underscore-convention.md)
- [What is the purpose of the `return self` idioms in your code examples?](./return_self_idiom.md)
- [Are there any prerequisites and recommended pre-readings?](./prerequisites.md)
25 changes: 25 additions & 0 deletions faq/return_self_idiom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# What is the purpose of the `return self` idioms in your code examples?

Many (if not all) of the object-oriented implementations in my code examples return `self` in their respective calls -- and scikit-learn does this, too! So, what is the rational behind a method that returns the the object itself? The answer is a rather simple one: "Chaining," which enables us to concatenate operations more conveniently (and efficiently) by feeding the answer of an operations into the next.

For example, an implementation such as

class Perceptron(object):
def __init__(self, …):

def fit(self, …):
return self

def predict(self, …):
return self

would allow us to write a compact notation such as

prediction = Perceptron().fit(X, y).predict(X)

in one line of code instead of

p = Perceptron()
p.fit(X, y)
prediction = p.predict(X)

0 comments on commit 2cdfee3

Please sign in to comment.