Python中方法鏈的使用方法
方法鏈(method chaining)是面向?qū)ο蟮木幊陶Z言中的一種常見語法,可以讓開發(fā)者在只引用對象一次的情況下,對同一個對象進行多次方法調(diào)用。舉個例子:
假設(shè)我們有一個Foo類,其中包含有兩個方法——bar和baz。
我們創(chuàng)建一個Foo類的實例:
foo = Foo()
如果不使用方法鏈,要想連續(xù)調(diào)用對象foo的bar和baz方法的話,我們得這樣做:
foo.bar() # Call method bar() on object foo. foo.baz() # Call method baz() on object foo.
如果使用方法鏈的話,我們就能這樣實現(xiàn): foo.bar().baz()
方法鏈的一個好處,是可以減少你使用對象名的次數(shù)。調(diào)用的方法越多,能夠減少的次數(shù)就越多。因此,這個方法也能一定程度上減少需要閱讀、測試、調(diào)試、維護的代碼數(shù)量。這個好處不大,但也是有用的。
請注意,方法鏈的一個限制是,只能用在不需要返回其他值的方法上,因為你需要返回self對象。即使Python支持用一個return語句返回多個值,也可能無法解決這個問題。
下面是在Python中實現(xiàn)方法鏈的一個示例:
class Person:
def name(self, value):
self.name = value
return self
def age(self, value):
self.age = value
return self
def introduce(self):
print "Hello, my name is", self.name, "and I am", self.age, "years old."
person = Person()
person.name("EarlGrey").age(21).introduce()
# => Hello, my name is EarlGrey and I am 21 years old.
上面那種實現(xiàn)可能太簡單了。下面我們來看一種更加現(xiàn)實的方法鏈使用方法:編寫一個字符串處理程序string_processor.py,支持方法鏈。
import copy
class StringProcessor(object):
'''
A class to process strings in various ways.
'''
def __init__(self, st):
'''Pass a string for st'''
self._st = st
def lowercase(self):
'''Make lowercase'''
self._st = self._st.lower()
return self
def uppercase(self):
'''Make uppercase'''
self._st = self._st.upper()
return self
def capitalize(self):
'''Make first char capital (if letter); make other letters lower'''
self._st = self._st.capitalize()
return self
def delspace(self):
'''Delete spaces'''
self._st = self._st.replace(' ', '')
return self
def rep(self):
'''Like Python's repr'''
return self._st
def dup(self):
'''Duplicate the object'''
return copy.deepcopy(self)
def process_string(s):
print
sp = StringProcessor(s)
print 'Original:', sp.rep()
print 'After uppercase:', sp.dup().uppercase().rep()
print 'After lowercase:', sp.dup().lowercase().rep()
print 'After uppercase then capitalize:', sp.dup().uppercase().\
capitalize().rep()
print 'After delspace:', sp.dup().delspace().rep()
def main():
print "Demo of method chaining in Python:"
# Use extra spaces between words to show effect of delspace.
process_string('hOWz It GoInG?')
process_string('The QUIck brOWn fOx')
main()
下面是這個程序的運行結(jié)果:
$ python string_processor.py Original: hOWz It GoInG? After uppercase: HOWZ IT GOING? After lowercase: howz it going? After uppercase then capitalize: Howz it going? After delspace: hOWzItGoInG? Original: The QUIck brOWn fOx After uppercase: THE QUICK BROWN FOX After lowercase: the quick brown fox After uppercase then capitalize: The quick brown fox After delspace: TheQUIckbrOWnfOx
綜上,我們可以發(fā)現(xiàn),方法鏈有其用處,不過過度使用可能不太好。
如何在Python中使用方法鏈?相信大家都有了一個大概的思路,希望本文所述對大家學習有所幫助。
相關(guān)文章
詳述numpy中的np.random.random()系列函數(shù)用法
本文主要介紹了詳述numpy中的np.random.random()系列函數(shù)用法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-03-03
簡單的Python2.7編程初學經(jīng)驗總結(jié)
這篇文章主要是作者寫給Python2.7編程初學者的經(jīng)驗總結(jié),側(cè)重于包管理、代碼調(diào)試等實際使用方面,需要的朋友可以參考下2015-04-04
Python使用textract實現(xiàn)從各種文件中提取文本信息
textract是一個強大的Python庫,可以用于從各種文件格式中提取文本,本文將介紹textract的使用場景,以及一些常用的Python代碼案例,希望對大家有所幫助2024-01-01
echarts動態(tài)獲取Django數(shù)據(jù)的實現(xiàn)示例
本文主要介紹了echarts動態(tài)獲取Django數(shù)據(jù)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08
Python編程源碼報錯解決方法總結(jié)經(jīng)驗分享
這篇文章主要介紹了在平時Python編程工作中一些源碼報錯的解決方法總結(jié)經(jīng)驗分享,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
Pyspider進行API接口抓取和數(shù)據(jù)采集的實現(xiàn)
Pyspider是一個基于Python的強大的網(wǎng)絡(luò)爬蟲框架,它提供了豐富的功能和靈活的擴展性,使我們可以輕松地進行數(shù)據(jù)的抓取和處理,本文主要介紹了Pyspider進行API接口抓取和數(shù)據(jù)采集的實現(xiàn),感興趣的可以了解一下2023-09-09
詳解python中Numpy的屬性與創(chuàng)建矩陣
這篇文章給大家分享了關(guān)于python中Numpy的屬性與創(chuàng)建矩陣的相關(guān)知識點內(nèi)容,有興趣的朋友們可以學習參考下。2018-09-09

