本文共 1475 字,大约阅读时间需要 4 分钟。
>>> 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. Deprecated since release 2.3. Instead, use the extended call syntax: function(*args, **keywords).>>>
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 asay('hello python!')apply(say,("hello python!",))def say_again(a,b): print a,bsay_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!转载地址:http://dnyai.baihongyu.com/