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

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

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

choice = raw_input("please input:\n").strip()[0].lower()
不少對於有經驗的程序員來講,這些都不是事,
但對於初學者來講,看到這樣的語法頭有點大。php

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

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

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

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

有的python初學者對python方法連續調用不是很清楚,像霧裏看花同樣。
python一切都是對象,對象調用它的方法,若是帶返回值,放回值也是對象,  
這個返回值也有方法,固然就能夠用點號調用它的方法,   
如此下去,就是python方法鏈調用也。

如何設計方法鏈python代碼

# coding:utf-8
"""
如何經過學習python學會編程
https://github.com/pythonpeixun/article/blob/master/python/how_to_learn_python.md
黃哥python遠程視頻培訓班
https://github.com/pythonpeixun/article/blob/master/index.md
黃哥python培訓試看視頻播放地址
https://github.com/pythonpeixun/article/blob/master/python_shiping.md
黃哥python培訓 諮詢qq:1465376564
"""


class Person(object):
    """方法鏈小sample"""

    def name(self, value):
        self.name = value
        return self # 返回實例對象本身才能再調用實例對象的方法。

    def work(self, value):
        self.working = value
        return self

    def introduce(self):
        print "你好, 個人名字:", self.name, ",個人工做:", self.working, ",教初學者學會編程!"

person = Person()
person.name("黃哥").work("黃哥python培訓").introduce()

php方法鏈代碼

<?php
	/*
	黃哥php培訓 諮詢qq:1465376564
	https://github.com/pythonpeixun/article/blob/master/php_education.md
	*/


	class Person{
	    public $name;
	    public $working;

	    public function setName($value){
	        $this->name = $value;
	        return $this;
	    }

	    public function work($value){
	        $this->working = $value;
	        return $this;
	    }

	    public function introduce(){
	        echo "你好, 個人名字:".$this->name.",個人工做:".$this->working.",教初學者學會編程!\n";
	    }
	}

	$person = new Person();
	$person->setName("黃哥")->work("黃哥php培訓")->introduce();

點擊黃哥python培訓試看視頻播放地址python

黃哥python遠程視頻培訓班git

相關文章
相關標籤/搜索