Python 如何从类方法向函数传递**KWARG
我需要为机器学习管道创建一个自定义transformer类。Python 如何从类方法向函数传递**KWARG,python,keyword-argument,Python,Keyword Argument,我需要为机器学习管道创建一个自定义transformer类。testfun实际上是一个通过rpy2访问的R函数testfun。 我想公开由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__(sel
testfun
实际上是一个通过rpy2访问的R函数<然后在test
类中使用code>testfun。
我想公开由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
输出:
(1, 1)
您的测试函数应该是这样的
def testfun(**kwargs):
... fetch each value using loop or similar...
这样叫testfun
testfun(a=1,b=2...)
在这里,你可以这样做
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()
函数
testkwargs
没有kwargs
变量。您需要将**kwargs
添加到testkwargs
参数中:def testkwargs(self,**kwargs):
为什么不将**kwargs
存储在\uuuuu init\uuugs
中,作为self.kwargs=kwargs
,然后返回testfun(**self.kwargs)
来自testkwargs
方法?kwargs
不是一个单独的命名参数(在普通意义上);它是单个方法的关键字参数的集合。它当然不是实例的属性,在一个函数中使用**kwargs
与在另一个函数中使用它无关。同意@SayandipDutta。调用\uuu dict\uuu.update()
将kwargs
的条目转换为test
实例的属性。您可以稍后通过调用testfun(self.x,self.y.self.a,self.b)
(假设xyaab
都已设置)。{“a”:1,“b”:2…}
不是关键字argument@Farhan.K编辑了我的答案。谢谢
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()