Python中return self的用法详解
作者:jclian91 时间:2022-06-08 08:43:32
在Python中,有些开源项目中的方法返回结果为self. 对于不熟悉这种用法的读者来说,这无疑使人困扰,本文的目的就是给出这种语法的一个解释,并且给出几个例子。
在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)
输出结果为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)
输出结果如下:
AttributeError: 'NoneType' object has no attribute 'bar'
那么return self返回的结果是什么呢?
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()))
输出结果为:
<class '__main__.Foo'>
可以发现,return self返回的是类的实例。
一个真实的例子:
sklearn模块中很多方法的返回结果为self, 比如大多数模型的fit()方法,例子如下:
from sklearn.linear_model import LogisticRegression
X = [[0,0], [0,1], [1,0], [1,1]]
y = [0, 1, 1, 0]
clf = LogisticRegression()
# fit函数返回的结果就是self, 允许链式调用
t = clf.fit(X,y).predict([[0,2]])
print(t)
输出:
[0]
总结
以上所述是小编给大家介绍的Python中return self的用法网站的支持!
来源:https://segmentfault.com/a/1190000015791934
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python爬取分析超级大乐透历史开奖数据第1/2页
![](https://img.aspxhome.com/file/2023/3/72013_0s.png)
QQ在线客服网页代码大全
![](https://img.aspxhome.com/file/UploadPic/20081/17/2008117205323775s.gif)
Django 日志配置按日期滚动的方法
Python列表list内建函数用法实例分析【insert、remove、index、pop等】
![](https://img.aspxhome.com/file/2023/2/86442_0s.jpg)
防止网站被采集的理论分析以及十条方法对策第1/2页
ASP实现GB2312字符与区位码的相互转换
Python 删除连续出现的指定字符的实例
Python图像处理库PIL的ImageFont模块使用介绍
![](https://img.aspxhome.com/file/2023/1/99211_0s.jpg)
Python实现将HTML转换成doc格式文件的方法示例
Python实现对照片中的人脸进行颜值预测
![](https://img.aspxhome.com/file/2023/2/80732_0s.png)
Firefox 3.5 新增加的支持(整理)
Python的三种主要模块介绍
给textarea增加长度限制的几种方法
用python登录带弱图片验证码的网站
![](https://img.aspxhome.com/file/2023/2/79692_0s.png)
在JScript中使用RecordSet对象的GetRows方法
基于Python列表解析(列表推导式)
Python实现AI自动玩俄罗斯方块游戏
![](https://img.aspxhome.com/file/2023/2/103682_0s.jpg)
基于python时间处理方法(详解)
Linux下PhpMyAdmin程序目录结构的安全管理
基于Python实现牛牛套圈小游戏的示例代码
![](https://img.aspxhome.com/file/2023/5/92235_0s.png)