简体   繁体   English

将方法作为带有可选参数的参数的方法

[英]Method that takes a method as a parameter with an optional parameter

I have two methods from a library that work in the same manner.我有两个以相同方式工作的库中的方法。 The difference is that one takes an additional, optional parameter.不同之处在于它需要一个额外的可选参数。 For example:例如:

def method1(a, b, c):
    ...

def method2(a, b, c, d=None):
    ...

I have to perform the same task on the results of these methods, so I have a method that combines them that looks like this:我必须对这些方法的结果执行相同的任务,因此我有一个将它们组合在一起的方法,如下所示:

def wrapper(method, a, b, c, d=None):

    ...

    if d:
        results = method(a, b, c, d=d)
    else:
        results = method(a, b, c)

    ...

This works, but as I add more methods that have different optional arguments it becomes cumbersome.这有效,但随着我添加更多具有不同可选参数的方法,它变得很麻烦。 Is there a way a better way to handle these parameters?有没有更好的方法来处理这些参数?

Here is some code that might accomplish what you're looking for.下面是一些可能会完成您正在寻找的代码。

You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs .您可以将一组方法传递给wrapper ,该函数将返回具有映射到kwargs关键字参数的任何方法的值。

def method1(a, b, c):
    return a, b, c


def method2(a, b, c, d=None):
    return a, b, c, d

methods = (
    method1,
    method2,
) # Collection of methods to run.

def wrapper(kwargs, methods=methods):
    """Loop over methods with kwargs."""
    for method in methods:
        try: # Call method with **kwargs
            return method(**kwargs) # Return value if keys in kwargs fit signature of method.
        except TypeError as err: # Handle error if keyword args don't match.
            print(f'err "{err}" for method "{method}')

kwargs_collection = (dict(zip(args, (f'value for arg: "{arg}"' for arg in args)))
                     for args in ('abcd', 'abc', ))




for test_kwargs in kwargs_collection:
    print(wrapper(test_kwargs))

OUTPUT :输出

err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"错误“method1() 在 0x7f900c2b7d90 处为方法“function method1”获得了意外的关键字参数“d”

('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"') ('arg 的值:“a”','arg 的值:“b”','arg 的值:“c”','arg 的值:“d”')

('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"') ('arg 的值:“a”','arg 的值:“b”','arg 的值:“c”')

For the wrapper function, I decided to just do something like the following as suggested in the comments:对于包装器函数,我决定按照评论中的建议执行以下操作:

def wrapper(method, *args):

    ...

    results = method(*args)

    ...

Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.正如另一个答案中所建议的那样,应该合并错误处理以确保传递正确的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM