如何通过类方法将** wargs传递给函数

问题描述 投票:0回答:1

我需要为机器学习管道创建自定义转换器类。 testfun实际上是通过rpy2访问的R函数。然后在testfun类中使用test。我想公开由testfun表示的R函数的所有参数,因此也要公开**kwargs。但是我不知道如何通过**kwargs。下面的代码引发错误。

def testfun(x=1, a=1, b=1, c=1):
    return x**a, b**c

class test(BaseEstimator, TransformerMixin):
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)
    def testkwargs(self):
        return testfun(**kwargs)
temp = test(x=1,a=1,b=2,c=3)
temp.testkwargs()

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-131-de41ca28c280> in <module>
      5         return testfun(**kwargs)
      6 temp = test(x=1,a=1,b=2,c=3)
----> 7 temp.testkwargs()

<ipython-input-131-de41ca28c280> in testkwargs(self)
      3         self.__dict__.update(**kwargs)
      4     def testkwargs(self):
----> 5         return testfun(**kwargs)
      6 temp = test(x=1,a=1,b=2,c=3)
      7 temp.testkwargs()

NameError: name 'kwargs' is not defined

提前感谢!

编辑:根据早期建议进行的更改没有太大帮助

class test(BaseEstimator, TransformerMixin):
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)
    def testkwargs(self, **kwargs):
        return testfun(**kwargs)
temp = test(x=2,a=1,b=2,c=3)
temp.testkwargs()

输出:

 (1, 1)
python kwargs
1个回答
0
投票

您的测试功能应该是这样。。

def testfun(**kwargs):
    ... fetch each value using loop or similar...

这样叫testfun。。

testfun(a=1,b=2...)

0
投票

这里您可以这样做。

© www.soinside.com 2019 - 2024. All rights reserved.