簡體   English   中英

如何將 **kwargs 從 class 方法傳遞給 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM