標籤:

跟黃哥學python序列文章之python方法鏈(method chaining)

寫這篇文章來由,有朋友說下面這樣的代碼看不懂。

choice = raw_input("please input:n").strip()[0].lower()

很多對於有經驗的程序員來說,這些都不是事,

但對於初學者來說,看到這樣的語法頭有點大。

這個其實是面向對象中方法鏈的概念。

請看維基百科上Method chaining的定義

Method chaining, also known as named parameter idiom, n is a common syntax for invoking multiple method calls n in object-oriented programming languages.n Each method returns an object, allowing the calls n to be chained together in a single statement without requiring n variables to store the intermediate results.n Local variable declarations are syntactic n sugar because of the difficulty humans have with deeply nested method calls.n A method chain is also known as a train wreck due to the increase n in the number of methods that come one after another in the same n line that occurs as more methods are chained togethern even though line breaks are often added between methods.n

具體在python中,請看黃哥的分析:

有的python初學者對python方法連續調用不是很清楚,像霧裡看花一樣。npython一切都是對象,對象調用它的方法,如果帶返回值,返回值也是對象, n這個返回值也有方法,當然就可以用點號調用它的方法, n如此下去,就是python方法鏈調用也。n

如何設計方法鏈python代碼

# coding:utf-8n"""n如何通過學習python學會編程nhttps://github.com/pythonpeixun/article/blob/master/python/how_to_learn_python.mdn黃哥python遠程視頻培訓班nhttps://github.com/pythonpeixun/article/blob/master/index.mdn黃哥python培訓試看視頻播放地址nhttps://github.com/pythonpeixun/article/blob/master/python_shiping.mdn黃哥python培訓 諮詢qq:1465376564n"""nnnclass Person(object):n """方法鏈小sample"""nn def name(self, value):n self.name = valuen return self # 返回實例對象自己才能再調用實例對象的方法。nn def work(self, value):n self.working = valuen return selfnn def introduce(self):n print "你好, 我的名字:", self.name, ",我的工作:", self.working, ",教初學者學會編程!"nnperson = Person()nperson.name("黃哥").work("黃哥python培訓").introduce()n

php方法鏈代碼

<?phpn /*n 黃哥php培訓 諮詢qq:1465376564n https://github.com/pythonpeixun/article/blob/master/php_education.mdn */nnn class Person{n public $name;n public $working;nn public function setName($value){n $this->name = $value;n return $this;n }nn public function work($value){n $this->working = $value;n return $this;n }nn public function introduce(){n echo "你好, 我的名字:".$this->name.",我的工作:".$this->working.",教初學者學會編程!n";n }n }nn $person = new Person();n $person->setName("黃哥")->work("黃哥php培訓")->introduce();n

推薦閱讀:

代碼優化指南:人生苦短,我用Python
由淺入深寫代理(3) -socks5 代理
Python數據分析及可視化實例之文本處理文本相似度(29)
玩點好玩的--知乎全部話題關係可視化(Docker+Flask+Bootstrap+echarts+uWSGI+Nginx)

TAG:Python |