python apply函式的用法
阿新 • • 發佈:2018-12-31
函式格式為:apply(func,*args,**kwargs)
輸出結果:
用途:當一個函式的引數存在於一個元組或者一個字典中時,用來間接的呼叫這個函式,並肩元組或者字典中的引數按照順序傳遞給引數
解析:args是一個包含按照函式所需引數傳遞的位置引數的一個元組,是不是很拗口,意思就是,假如A函式的函式位置為 A(a=1,b=2),那麼這個元組中就必須嚴格按照這個引數的位置順序進行傳遞(a=3,b=4),而不能是(b=4,a=3)這樣的順序
kwargs是一個包含關鍵字引數的字典,而其中args如果不傳遞,kwargs需要傳遞,則必須在args的位置留空
apply的返回值就是函式func函式的返回值
def function(a,b): print(a,b) apply(function,('good','better')) apply(function,(2,3+6)) apply(function,('cai','quan')) apply(function,('cai',),{'b':'caiquan'}) apply(function,(),{'a':'caiquan','b':'Tom'}) #--使用 apply 函式呼叫基類的建構函式 class Rectangle: def __init__(self, color="white", width=10, height=10): print "create a", color, self, "sized", width, "x", height class RoundedRectangle(Rectangle): def __init__(self, **kw): apply(Rectangle.__init__, (self,), kw) rect = Rectangle(color="green", height=100, width=100) rect = RoundedRectangle(color="blue", height=20)
輸出結果:
('good', 'better')
(2, 9)
('cai', 'quan')
('cai', 'caiquan')
('caiquan', 'Tom')
create a green <__main__.Rectangle instance at 0x0678FA08> sized 100 x 100
create a blue <__main__.RoundedRectangle instance at 0x06620468> sized 10 x 20