简体   繁体   English

为 Python 中的 function 传递相同的参数名称

[英]Passing same argument names for a function in Python

In python, I have a class with functions printing certain outputs, of which each has default parameters but those can be changed, like在 python 中,我有一个 class 具有打印某些输出的功能,其中每个都有默认参数,但可以更改,比如

def func1(self,a='a', b='b'):
    return something
def func2(self,c='c', d='d'):
    return something 

Lots of other functions of a similar kind too.还有很多其他类似的功能。

I created another function that can take those functions with parameters and can do something with them, ie我创建了另一个 function 可以使用带参数的函数并可以对它们做一些事情,即

def foo(self, default,*args,**kwargs):
    df=self.df
    if default == True:
        args = self.list1
    else:
        for fname in args:
            getattr(self, fname)(*kwargs)
            df['appending_array'] = df.apply(lambda...

In the effect I'd like to be able to call something like object.foo(False, func2,func11,d='z') Unfortunately in the loop, when I change d to 'z', it changes the first argument of each function that is iterated, instead of the actual parameter d from the function I want.在效果上我希望能够调用类似object.foo(False, func2,func11,d='z') 的东西不幸的是,在循环中,当我将 d 更改为 'z' 时,它会更改第一个参数每个被迭代的 function ,而不是我想要的 function 中的实际参数 d 。

Is there a possibility to either rearrange it so I can pass the original parameters of each passed function, or configure **kwarg so it can refer to the original parameters' names of each function?是否有可能重新排列它以便我可以传递每个传递的 function 的原始参数,或者配置 **kwarg 以便它可以引用每个 function 的原始参数名称?

Many thanks for any help/advice非常感谢您的任何帮助/建议

You need to unpack the kwargs with dictionary unpacking using two stars:您需要使用两颗星通过字典解包来解包 kwargs:

getattr(self, fname)(**kwargs)

And I think you also need to provide self as the first argument since these are unbound methods:而且我认为您还需要提供 self 作为第一个参数,因为这些是未绑定的方法:

getattr(self, fname)(self,**kwargs)

So, if I understand correctly, you want to write it such that if, for example, d is present in the foo call, it is solely passed to all functions in args that have d as an input argument (in this case, func2 )?因此,如果我理解正确,您希望这样编写它,例如,如果d存在于foo调用中,则它仅传递给args中以d作为输入参数的所有函数(在本例中为func2 ) ?

If so, then you want to determine all input arguments that each function can take.如果是这样,那么您要确定每个 function 可以占用的所有输入 arguments。 Luckily, Python has a function that allows you to do just that: inspect.signature .幸运的是,Python 有一个 function 可以让你做到这一点: inspect.signature

So, you could rewrite it like this (I am assuming you wanted to pass the names of the functions as args , not the actual functions themselves):因此,您可以像这样重写它(我假设您想将函数的名称作为args传递,而不是实际的函数本身):

from inspect import signature

def foo(self, default, *args, **kwargs):
    df=self.df

    if default:
        args = self.list1
    else:
        for fname in args:
            # Obtain function
            func = getattr(self, fname)

            # Obtain signature of this function
            f_sig = signature(func)

            # Create dict with values for this function, updating with values from kwargs
            # Make sure to skip 'self'
            f_kwargs = {argname: kwargs.get(argname, argpar.default)
                        for argname, argpar in f_sig.parameters.items()
                        if (argname != 'self')}

            # Call this function
            f_out = func(**f_kwargs)

            # Perform some operations on the output of this function
            df['appending_array'] = df.apply(lambda...

Keep in mind that this only works if every function that is ever passed as args solely takes optional arguments.请记住,这仅在每个作为args传递的 function 仅采用可选的 arguments 时才有效。 If one argument is mandatory, it must be passed to kwargs .如果一个参数是强制性的,则必须将其传递给kwargs

PS: I am however unsure what the use of the args = self.list1 for if default is. PS:但是,我不确定args = self.list1if default用途是什么。 Because that part is incompatible with everything else.因为那部分与其他一切都不兼容。

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

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