2012-03-18 43 views

回答

4

語言Java和Python是很好的例子來說明這一點。在Python中,對象被顯式地傳遞每當一個類的方法被定義:

class Example(object): 

    def method(self, a, b): 
     print a, b 
     # The variable self can be used to access the current object 

這裏,對象self被顯式地傳遞作爲第一個參數。這意味着,

e = Example() 
e.method(3, 4) 

是有效地與調用method(e, 3, 4)如果method是一個函數。

然而,在Java中的第一個參數沒有明確提及:

public class Example { 
    public void method(int a, int b) { 
     System.out.println(a + " " + b); 
     // The variable this can be used to access the current object 
    } 
} 

在Java中,這將是:

Example e = Example(); 
e.method(3, 4); 

實例e傳遞給method很好,但特殊的變量可以使用this來訪問它。

當然,對於函數每個參數明確,因爲每個參數在兩個函數定義並在函數被調用提到過。如果我們定義

def func(a, b, c): 
    print a, b, c 

那麼我們就可以用func(1, 2, 3)調用它,這意味着所有的參數都是明確地傳遞。

+0

隱式參數是定義方法時不需要提及的參數嗎?在你的Python例子中,對象'self'定義在哪裏?它可以是任何其他名稱嗎?你的類「Example」做了什麼?(object)?什麼時候需要訪問當前對象?非常感謝西蒙! – 2012-03-21 20:28:01

+0

隱式參數是在方法的定義中沒有提到的參數(在Java中沒有提到這個,但你仍然可以在方法本身中使用它)。對象'self'是對象'e':我們調用'e.method(3,4)',這意味着Python使用參數'e'調用'method'(在方法:'self'中) '3'('A')和'4'('B')。 '(object)'表示類'Example'具有'object'作爲父類;這與老風格和新風格類有關(在這裏沒有空間來解釋)。最後,你可以在類的方法中訪問當前對象(比如Python中的'self')。 – 2012-03-21 20:39:28

1

在這種情況下,一個方法可以被認爲是一個函數,它可以訪問它綁定的對象。該對象的任何屬性都可以從該方法中訪問,即使它們沒有出現在函數的簽名中。你沒有指定一種語言,但讓我舉一個PHP例子,因爲它非常流行,即使你沒有使用它也很容易閱讀。

編輯:語言在我寫完之後添加;也許有人可以根據需要將其翻譯成其中一種語言。

<?php 
/* Explicit passing to a function */ 
function f($a, b) 
{ 
    return $a + b; 
} 

// f(1, 2) == 3 

class C 
{ 
    public $a, $b; 

    /* $a and $b are not in the parameter list. They're accessed via the special $this variable that points to the current object. */ 
    public function m() 
    { 
     return $this->a + $this->b; 
    } 

} 

$o = new C(); 
$o->a = 1; 
$o->b = 2; 
//$o->m() == 3 
相關問題