在 Python 中将参数从一个函数传递到另一个函数的最佳方式
Best Way to Pass Arguments from One Function to Another in Python
我有一个执行特定任务的函数,这个函数有很多选项,包括命名和未命名的选项。例如:
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
选项。此外,关键字参数必须跟在位置参数之后。另外这里好像不够用,因为我只是想传递一些参数,而不是全部。
其他相关链接(虽然我不相信他们成功地解决了我的问题):
can I pass all positional arguments from one function to another in python?
do_lots_of_stuff("Bob","Mary",activity_1='run',activity_2='jump', eat_fruit_args=["John"], eat_fruit_kwargs={"a_number": 5, "a_fruit": "apples"}):
eat_fruit(*eat_fruit_args, **eat_fruit_kwargs)
return(f'''{a} and {b} {activity_1} and {activity_2}''')
您可以传递和转发参数和关键字参数。参数采用列表的形式。关键字参数 (kwargs) 采用字典形式,键为字符串,值为相关关键字值。
我有一个执行特定任务的函数,这个函数有很多选项,包括命名和未命名的选项。例如:
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
选项。此外,关键字参数必须跟在位置参数之后。另外
其他相关链接(虽然我不相信他们成功地解决了我的问题):
can I pass all positional arguments from one function to another in python?
do_lots_of_stuff("Bob","Mary",activity_1='run',activity_2='jump', eat_fruit_args=["John"], eat_fruit_kwargs={"a_number": 5, "a_fruit": "apples"}):
eat_fruit(*eat_fruit_args, **eat_fruit_kwargs)
return(f'''{a} and {b} {activity_1} and {activity_2}''')
您可以传递和转发参数和关键字参数。参数采用列表的形式。关键字参数 (kwargs) 采用字典形式,键为字符串,值为相关关键字值。