python apply()函数

>>> help(apply)
Help on built-in function apply in module __builtin__:
apply(...)
    apply(object[, args[, kwargs]]) -> value
    Call a callable object with positional arguments taken from the tuple args,
    and keyword arguments taken from the optional dictionary kwargs.
    Note that classes are callable, as are instances with a __call__() method.
    <span style="color:#ff0000;">Deprecated since release 2.3. Instead, use the extended call syntax:
        function(*args, **keywords).</span>
>>> 

args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任何参数都不会被传递。
kwargs是一个包含关键字参数的字典。
apply()的返回值就是object()的返回值。
apply()的元素参数是有序的,元素的顺序必须和object()形式参数的顺序一致。

1》执行不带参数的函数

def say():
    print 'hello python!'
    
say()
apply(say)
结果:
hello python!
hello python!
2》函数只带元组的参数

def say(a):
    print a

say('hello python!')
apply(say,("hello python!",))

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

say_again('hello','python!')
apply(say_again,('hello','python!'))
结果:
hello python!
hello python!
hello python!
hello python!
3》函数带关键字参数

def say(a=1,b=2):
    print a,b
 
def haha(**kw):
    print kw
    print type(kw)
    say()
    say(kw)#将kw传给a, b取默认值
    apply(say,(),kw)
 
haha(a='hello',b='python!')
结果:
{'a': 'hello', 'b': 'python!'}
<type 'dict'>
1 2
{'a': 'hello', 'b': 'python!'} 2

hello python!

又如:

def say(x,y,a=1,b=2):  
    print x,y,a,b  
   
def haha(*args,**kw):
    print args,type(args)
    print kw,type(kw)
    apply(say,args,kw)  
   
haha(1,2,a='hello',b='python!')  

结果:

(1, 2) <type 'tuple'>
{'a': 'hello', 'b': 'python!'} <type 'dict'>
1 2 hello python!





  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值