forked from rasbt/python-machine-learning-book
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
the puprose of the
return self
idioms in my code examples
- Loading branch information
Showing
2 changed files
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |