【发布时间】:2021-07-14 05:49:51
【问题描述】:
我有一个执行特定任务的函数,该函数有许多选项,包括命名选项和未命名选项。例如:
def eat_fruit(x,a_number=None , a_fruit=None):
return(f'{x} ate {str(a_number)} {a_fruit}')
#call the function
eat_fruit("John",a_number=5,a_fruit='apples') #outputs 'John ate 5 apples'
现在,我有另一个函数,它有很多选项,例如:
def do_lots_of_stuff(a,b,activity_1=None,activity_2=None):
return(f'''{a} and {b} {activity_1} and {activity_2}''')
do_lots_of_stuff("Bob","Mary",activity_1='run',activity_2='jump') #returns "Bob and Mary run and jump"
我想让函数do_lots_of_stuff 调用函数eat_fruit,有时带有选项。但是,我不清楚如何以一种直接的方式将选项从一个传递到另一个。
理想情况下,我正在寻找类似的东西:
#This code does not work; it demos the type of functionality I am looking for.
do_lots_of_stuff("Bob","Mary",activity_1='run',activity_2='jump', eat_fruit_options={*put_options_here*}):
eat_fruit(eat_fruit_options)
return(f'''{a} and {b} {activity_1} and {activity_2}''')
请注意,这不能通过do_lots_of_stuff(*do_lots_of_stuff_options*, *eat_fruit_options*) 完成,因为eat_fruit 的选项无效do_lots_of_stuff 选项。此外,关键字参数必须在位置参数之后。另外this solution在这里似乎不够用,因为我只想传递一些参数,而不是全部。
其他相关链接(虽然我不相信他们能成功解决我的问题):
can I pass all positional arguments from one function to another in python?
【问题讨论】:
标签: python-3.x function arguments