Python中return self的用法详解

yipeiwu_com6年前Python基础

在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的用法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

深入了解Python中pop和remove的使用方法

Python关于删除list中的某个元素,一般有两种方法,pop()和remove()。 remove() 函数用于移除列表中某个值的第一个匹配项。 remove()方法语法: list...

Python手机号码归属地查询代码

Python手机号码归属地查询代码

简单的一个例子,是以前用Dephi写的,前不久刚实现了一个在Python中使用Delphi控件来编写界面程序,于是趁热写一个类似的的查询方案。 本实例是通过www.ip138.com这...

CentOS 7 安装python3.7.1的方法及注意事项

安装wget yum -y install wget 创建一个download目录用于下载各种安装包 mkdir download 切换到刚创建的download目录中 cd downl...

python中的decorator的作用详解

1、概念 装饰器(decorator)就是:定义了一个函数,想在运行时动态增加功能,又不想改动函数本身的代码。可以起到复用代码的功能,避免每个函数重复性编写代码,简言之就是拓展原来函数功...

Python3处理文件中每个词的方法

本文实例讲述了Python3处理文件中每个词的方法。分享给大家供大家参考。具体实现方法如下: ''''' Created on Dec 21, 2012 处理文件中的每个词 @...