Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python apply 函式的用法詳解

apply 函式的具體含義是:apply(func [, args [, kwargs ]]) 用於當函式的參數已經存在於一個元組或字典中時,間接呼叫該函式。args 是一個包含按位置傳遞參數的元組,若省略 args 則不傳遞任何參數;kwargs 則是包含關鍵字參數的字典。

apply() 的回傳值就是 func() 的回傳值,且 apply() 的位置參數是有序的,順序必須與 func() 的形式參數一致。

以下用幾個例子詳細說明。

一、呼叫沒有參數的函式

def say():
 print 'say in'

apply(say)

輸出結果為 say in。

二、函式只帶元組參數

def say(a, b):
 print a, b

apply(say,("hello", "老王python"))

輸出結果為 hello 老王python。

三、函式帶關鍵字參數

def say(a=1,b=2):
 print a,b

def haha(**kw):
 #say(kw)
 apply(say,(),kw)

print haha(a='a',b='b')

輸出結果為 a b。

Copyright © Linux教程網 All Rights Reserved