【问题标题】:Best Way to Pass Arguments from One Function to Another in Python在 Python 中将参数从一个函数传递到另一个函数的最佳方法
【发布时间】: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?

Passing variables between functions in Python

Passing value from one function to another in Python

【问题讨论】:

    标签: python-3.x function arguments


    【解决方案1】:
    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)采用字典的形式,键为字符串,值作为相关的关键字值。

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多