Python函數(shù)比我們想象的更為靈活。由于Python函數(shù)是對(duì)象,所以函數(shù)對(duì)象可以賦值給其他的名字、傳遞給其他函數(shù)、嵌入到數(shù)據(jù)結(jié)構(gòu)、從一個(gè)函數(shù)返回給另一個(gè)函數(shù),等等,就好像它們是簡(jiǎn)單的數(shù)字或字符串。
下面的代碼演示了把一個(gè)函數(shù)對(duì)象賦給其他的名稱并調(diào)用它:
>>>def echo(message): # Name echo assigned to function object
... print(message)
...
>>>echo('Direct call') # Call object through original name
Direct call
>>>x = echo # Now x references the function too
>>>x('Indirect call!') # Call object through name by x()
Indirect call!
下面的代碼演示了將函數(shù)通過參數(shù)來進(jìn)行傳遞:
>>>def indirect(func,arg):
... func(arg) # Call the passed-in object by adding ()
...
>>>indirect(echo,'Argument call!') # Pass the function to another function
Argument call!
我們甚至可以把函數(shù)對(duì)象填入到數(shù)據(jù)結(jié)構(gòu)中,就好像它們是整數(shù)或字符串一樣:
>>>schedule = [ (echo,'Spam!'),(echo,'Ham!') ]
>>>for (func,arg) in schedule:
... func(arg) # Call functions embedded in containers
...
Spam!
Ham!
函數(shù)也可以創(chuàng)建并返回以便之后使用:
>>>def make(label): # Make a function but don't call it
... def echo(message):
... print(label + ':' + message)
... return echo
...
>>>F = make('Spam') # Label in enclosing scope is retained
>>>F('Ham!') # Call the function that make returned
Spam:Ham!
>>>F('Eggs!')
Spam:Eggs!
Python的通用對(duì)象模式和無須類型聲明使得該編程語言有了令人驚訝的靈活性。
-
函數(shù)
+關(guān)注
關(guān)注
3文章
4331瀏覽量
62622 -
代碼
+關(guān)注
關(guān)注
30文章
4788瀏覽量
68616 -
python
+關(guān)注
關(guān)注
56文章
4797瀏覽量
84690
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論