Python函數比我們想象的更為靈活。由于Python函數是對象,所以函數對象可以賦值給其他的名字、傳遞給其他函數、嵌入到數據結構、從一個函數返回給另一個函數,等等,就好像它們是簡單的數字或字符串。
下面的代碼演示了把一個函數對象賦給其他的名稱并調用它:
>>>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!
下面的代碼演示了將函數通過參數來進行傳遞:
>>>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!
我們甚至可以把函數對象填入到數據結構中,就好像它們是整數或字符串一樣:
>>>schedule = [ (echo,'Spam!'),(echo,'Ham!') ]
>>>for (func,arg) in schedule:
... func(arg) # Call functions embedded in containers
...
Spam!
Ham!
函數也可以創建并返回以便之后使用:
>>>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的通用對象模式和無須類型聲明使得該編程語言有了令人驚訝的靈活性。
-
函數
+關注
關注
3文章
4346瀏覽量
63013 -
代碼
+關注
關注
30文章
4837瀏覽量
69121 -
python
+關注
關注
56文章
4811瀏覽量
85075
發布評論請先 登錄
相關推薦
評論