为不同的功能分开** kwargs [英] Separating **kwargs for different functions

查看:155
本文介绍了为不同的功能分开** kwargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个以多个函数为参数的高阶函数,该函数如何将关键字参数传递给函数参数?

>

  def eat(food ='eggs',how_much = 1):
print(food * how_much)

$ b $ def parrot_is(state ='dead'):
print(这只鹦鹉是%s。%state)


def skit(* lines,** kwargs):行
行:
行(** kwargs)

skit(吃,parrot_is)#eggs \\\
这个鹦鹉已经死了。
skit(eat,parrot_is,food ='spam',how_much = 50,state ='ex-parrot')#error

state 不是关键字arg eat 那么skit只能通过关键字参数与它调用的函数相关吗?

解决方案

您可以过滤 kwargs func_code.co_varnames 的函数:

  def skit(* lines,** kwargs):行

行(** {key:key的值,kwargs.iteritems的值()
如果key in line .func_code.co_varnames})

另请参阅:你可以列出Python函数接收的关键字参数吗?


Given a higher order function that takes multiple functions as arguments, how could that function pass key word arguments to the function arguments?

example

def eat(food='eggs', how_much=1):
    print(food * how_much)


def parrot_is(state='dead'):
    print("This parrot is %s." % state)


def skit(*lines, **kwargs):
    for line in lines:
        line(**kwargs)

skit(eat, parrot_is)  # eggs \n This parrot is dead.
skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot') # error

state is not a keyword arg of eat so how can skit only pass keyword args relevant the function that it is calling?

解决方案

You can filter the kwargs dictionary based on func_code.co_varnames of a function:

def skit(*lines, **kwargs):
    for line in lines:
        line(**{key: value for key, value in kwargs.iteritems() 
                if key in line.func_code.co_varnames})

Also see: Can you list the keyword arguments a Python function receives?

这篇关于为不同的功能分开** kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆