【问题标题】:Calling a function depending on number of parametres in Python根据 Python 中的参数数量调用函数
【发布时间】:2021-02-21 08:35:12
【问题描述】:

想象一下这种情况:

def foo1(item1, item2, item3):
    pass


def foo2(item4, item5):
    pass


item_to_pass = "random item"
x = 3

我需要调用一个接受 x 参数的函数。作为参数,我想传递 item_to_pass(或任何其他变量)。

基本上,我知道如何使用检查模块找出一个函数有多少个参数。但我不知道如何使用这些参数调用某个函数(假设这些参数都是相同的)。另请注意,我不能将项目列表作为参数而不是多个参数传递,我需要有不同数量的参数并基于该调用函数。

你有什么想法,我该如何解决这个问题?

【问题讨论】:

标签: python function parameters


【解决方案1】:

这是你要找的东西吗:

import inspect

def foo1(item1, item2, item3):
    print("foo1 called")

def foo2(item4, item5):
    print("foo2 called")

def fooWrapper(*args):
    # map functions to function's arguments
    funcs = {fn: len(inspect.getfullargspec(fn).args) for fn in (foo1, foo2)}

    # lookup all functions that take the same amount of arguments as given.
    for fn, argLen in funcs.items():
        if len(args) == argLen:
            fn(*args)
            break

item_to_pass = "random item"
x = 3
foo1_Argument = "foo"

fooWrapper(item_to_pass, x)
fooWrapper(item_to_pass, x, foo1_Argument)

输出:

foo2 called
foo1 called

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2017-10-20
    • 2020-09-15
    • 2013-08-11
    • 2018-01-02
    • 2017-01-19
    相关资源
    最近更新 更多