搜索
您的当前位置:首页正文

Python中return self的用法

来源:二三娱乐

在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(这个是笔者自己的翻译: 链式调用).

例子:

输出结果为3.

把bar()方法改为返回return None, 则上述代码会出错。

输出结果如下:

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

那么return self返回的结果是什么呢?

输出结果为:

可以发现,return self返回的是类的实例。

一个真实的例子:

sklearn模块中很多方法的返回结果为self, 比如大多数模型的fit()方法,例子如下:

输出:

Top