2013-03-29 37 views
-1

我目前正在學習python,使用「Think Python」,其中我通過下面的某段代碼進行學習,並且我是一名初學者程序員,我不明白它是如何工作的,請解釋一下下面的代碼以及它背後的各種概念。與Python中函數對象的使用相混淆

excercise:函數對象是一個值,你可以賦值給變量或作爲參數傳遞。對於 例如,do_twice是一個函數,函數對象作爲參數,並調用它兩次:

def do_twice(f): 
    f() 
    f() 

# Here’s an example that uses do_twice to call a function named print_spam twice. 

def print_spam(): 
    print 'spam' 

do_twice(print_spam) 

這個代碼給出了O/P爲 垃圾 垃圾 我不知道我怎麼和想更深入的解釋這個概念

+2

你的問題是什麼?你有什麼不明白? – BrenBarn

回答

3

Python函數是第一類對象。就像其他對象一樣,它們可以分配給變量並傳遞。

>>> def print_spam(): 
...  print 'spam' 
... 
>>> print_spam 
<function print_spam at 0x105722ed8> 
>>> type(print_spam) 
<type 'function'> 
>>> another_name = print_spam 
>>> another_name 
<function print_spam at 0x105722ed8> 
>>> another_name is print_spam 
True 
>>> another_name() 
spam 

在上面的例子會話我玩的print_spam函數對象,將其分配給another_name,然後經由其他變量調用它。

Think Python引用的所有代碼都是將print_spam作爲參數傳遞給函數do_twice,該函數將其稱爲參數f兩次。

+0

仍然不清楚爲什麼以及他們如何使用f() –

+0

'f'是函數'do_twice()'的一個參數。通過賦予該函數對另一個函數的引用,「f」變成對該另一函數的引用。加入'()'然後調用引用的函數。 –

+0

我終於知道了。 print_spam = F 和do_twice F()= print_spam內部() 由於馬亭皮特斯 –