前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python apply()函数

python apply()函数

作者头像
py3study
发布2020-01-06 14:33:45
1.6K0
发布2020-01-06 14:33:45
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
>>> 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》执行不带参数的函数

代码语言:javascript
复制
def say():
    print 'hello python!'
    
say()
apply(say)

结果: hello python! hello python! 2》函数只带元组的参数

代码语言:javascript
复制
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》函数带关键字参数

代码语言:javascript
复制
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!

又如:

代码语言:javascript
复制
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!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档