溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Python中使用return self方法

發(fā)布時間:2021-01-06 15:57:21 來源:億速云 閱讀:338 作者:Leah 欄目:開發(fā)技術(shù)

怎么在Python中使用return self方法?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

在Python中,return self的作用為:

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.

通俗的說法是, allow chaining

例子:

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)

輸出結(jié)果為4.

把bar()方法改為返回return None, 則上述代碼會出錯。

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)

輸出結(jié)果如下:

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

那么return self返回的結(jié)果是什么呢?

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()))

輸出結(jié)果為:

<class '__main__.Foo'>

可以發(fā)現(xiàn),return self返回的是類的實(shí)例。

一個真實(shí)的例子:

sklearn模塊中很多方法的返回結(jié)果為self, 比如大多數(shù)模型的fit()方法,例子如下:

from sklearn.linear_model import LogisticRegression
X = [[0,0], [0,1], [1,0], [1,1]]
y = [0, 1, 1, 0]
clf = LogisticRegression()
# fit函數(shù)返回的結(jié)果就是self, 允許鏈?zhǔn)秸{(diào)用
t = clf.fit(X,y).predict([[0,2]])
print(t)

輸出:

[0]

關(guān)于怎么在Python中使用return self方法問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI