![](/img/trans.png)
[英]Is there a cleaner way to pass kwargs from class to a function
[英]how to pass **kwargs to a function from a class method
我需要为机器学习管道创建自定义转换器 class。 testfun
其实是一个通过rpy2访问的R function。 然后在test
testfun
中使用 testfun。我想公开由 testfun 表示的 R function 的所有testfun
,因此**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()
Output:
(1, 1)
在这里你可以这样做。
def testfun(x=1, a=1, b=1, c=1):
return x**a, b**c
class test():
def __init__(self, **kwargs):
self.__dict__.update(**kwargs)
self.kwargs = kwargs
def testkwargs(self):
return testfun(**self.kwargs)
temp = test(x=1,a=1,b=2,c=3)
temp.testkwargs()
你的测试 function 应该是这样的..
def testfun(**kwargs):
... fetch each value using loop or similar...
像那样调用 testfun ..
testfun(a=1,b=2...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.