Python实现类似jQuery使用中的链式调用的示例
作者:mattkang 时间:2021-09-20 00:16:55
关于jQuery的链式调用
真正有意义的链式调用也就是方法链(method chaining)。方法链这个词是有的,而且使用的很广泛。其实很多人口中的“链式调用”实际上就是指方法链。但是“链式调用”这个词语还可以描述函数调用链,所以让它自身的存在价值变得难以理解。
我总结的方法链的价值有这么几个:
1. 让调用过程更接近自然语言。
2. 把原本参数列表复杂的方法化作多个参数列表简单的方法来使用。
3. 减少不必要的代码量。
这个三点都是有益于开发的,所以方法链的存在很有意义。jQuery的很多东西就是使用了方法链的概念。
总之,如果“链式调用”这个词还是尽量别用,因为无法从字面判断含义。除非你想说明的是上面这个脑残东西,你可以用“链式调用”去说,如果只是想描述方法链的概念,就直接说方法链就行了。
Python实现链式调用
用过jquery的一般都知道在jquery中可以链式调用,代码简洁优雅。比如$(“a”).addClass(“test”).show().html(“foo”);。
在redis-py中的pipeline中也可以链式调用,比如pipe.set('foo', 'bar').sadd('faz', 'baz').incr('auto_number').execute() 。
那么究竟怎么实现的呢?
很简单,返回对象自己就行了,即return self.
废话不多说,上代码。
class Person:
def name(self, name):
self.name = name
return self
def age(self, age):
self.age = age
return self
def show(self):
print "My name is", self.name, "and I am", self.age, "years old."
p = Person()
p.name("Li Lei").age(15).show()
标签:Python,链式调用
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用anaconda的pip安装第三方python包的操作步骤
2022-11-20 04:05:22
python列表的逆序遍历实现
2021-08-02 02:01:28
![](https://img.aspxhome.com/file/2023/4/131764_0s.png)
Keras中的多分类损失函数用法categorical_crossentropy
2023-06-23 12:25:37
![](https://img.aspxhome.com/file/2023/5/63935_0s.jpg)
详解Python自动化中这八大元素定位
2023-06-04 18:25:34
![](https://img.aspxhome.com/file/2023/5/124935_0s.png)
pandas添加新列的5种常见方法
2022-08-09 16:45:03
![](https://img.aspxhome.com/file/2023/8/109618_0s.jpg)
python实现从尾到头打印单链表操作示例
2021-12-20 00:09:32
浅谈python中拼接路径os.path.join斜杠的问题
2023-08-21 23:41:23
python基础之共有操作
2021-01-29 23:42:18
![](https://img.aspxhome.com/file/2023/6/90776_0s.png)
php报错502badgateway解决方法
2023-11-22 13:12:06
pip install如何指定包的安装路径
2022-05-28 03:38:47
![](https://img.aspxhome.com/file/2023/3/133293_0s.jpg)
python基于pygame实现响应游戏中事件的方法(附源码)
2021-03-26 07:15:55
![](https://img.aspxhome.com/file/2023/0/124910_0s.png)
Python使用ntplib库同步校准当地时间的方法
2021-10-07 13:55:32
python3 cookbook中常遇问题解答
2022-09-07 09:07:05
python 时间信息“2018-02-04 18:23:35“ 解析成字典形式的结果代码详解
2021-10-28 05:37:14
![](https://img.aspxhome.com/file/2023/5/127645_0s.png)
python 3利用BeautifulSoup抓取div标签的方法示例
2023-09-17 02:57:48
Python之列表的append()方法最容易踩的坑
2022-05-14 18:56:53
如何让对方在线查看我的程序代码?
2010-05-13 16:34:00
Python绑定方法与非绑定方法详解
2021-04-12 00:20:19
Python3自动生成MySQL数据字典的markdown文本的实现
2021-04-29 15:21:18
python正则实现计算器功能
2022-06-13 06:14:00