GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — python-machine-learning-book/faq/return_self_idiom.md at master · GS-/python-machine-learning-book

Expand file tree

/

return_self_idiom.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
25 lines (16 loc) · 912 Bytes
/

return_self_idiom.md

Copy path

File metadata and controls

25 lines (16 loc) · 912 Bytes
Raw
Copy raw file
Download raw file
Edit and raw actions

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)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.