Python函數(shù)比我們想象的更為靈活。由于Python函數(shù)是對象,所以函數(shù)對象可以賦值給其他的名字、傳遞給其他函數(shù)、嵌入到數(shù)據(jù)結(jié)構(gòu)、從一個(gè)函數(shù)返回給另一個(gè)函數(shù),等等,就好像它們是簡單的數(shù)字或字符串。
下面的代碼演示了把一個(gè)函數(shù)對象賦給其他的名稱并調(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ù)對象填入到數(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的通用對象模式和無須類型聲明使得該編程語言有了令人驚訝的靈活性。
-
函數(shù)
+關(guān)注
關(guān)注
3文章
4277瀏覽量
62323 -
代碼
+關(guān)注
關(guān)注
30文章
4722瀏覽量
68231 -
python
+關(guān)注
關(guān)注
55文章
4767瀏覽量
84375
發(fā)布評論請先 登錄
相關(guān)推薦
評論