Article From:https://www.cnblogs.com/jclian91/p/9377995.html

  In Python, some methods in open source projects return self. This is undoubtedly troubling for readers unfamiliar with this usage. The purpose of this article is to give an explanation of this syntax and give several examples.

  In Python, the role of return self is: (English original, author level is limited, temporarily not translated)

Returning self from a method simply means that your method returns a reference to the instance object on which it was called. This can sometimes be seen in use with object oriented APIs that are designed as a fluent interface that encourages method cascading.

The popular saying is that allow chaining (this is the author’s own translation: chain call).

  Example:

class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return self

f = Foo()
f.bar().bar().bar()
print(f.myattr)

The output is 4..

To change the bar () method to return to return None, the above code will go wrong.

class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return None

f = Foo()
f.bar().bar().bar()
print(f.myattr)

The output is as follows:

AttributeError: 'NoneType' object has no attribute 'bar'

  So what is the result of return self’s return?

class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    #return None
    return self

f = Foo()
print(type(f.bar()))

The output is:

<class '__main__.Foo'>

It can be found that return self returns instances of classes.

  A real example:

sklearnThe return result of many methods in the module is self, such as most fit () methods. Examples are as follows:

from sklearn.linear_model import LogisticRegression

X = [[0,0], [0,1], [1,0], [1,1]]
y = [0, 1, 1, 0]

clf = LogisticRegression()
# fitThe result returned by the function is self, allowing chain calls.T = clf.fit (X, y).Predict ([[0,2]])Print (T)

Output:

[0]
Link of this Article: The usage of return self in Python

Leave a Reply

Your email address will not be published. Required fields are marked *