通过多个函数/类/方法传递任意数量的变量

时间:2017-10-03 13:46:47

标签: python python-2.7 python-3.x kwargs

我有一个类看起来像这样的方法

class A(object):
    def __init__(self, strat):
        self.strat_cls = strat
        self._genInstances()

    def _genInstances(self):
        self.strat = self.strat_cls(self.x, self.y)

和strat_cls:

class strat1(Strat):   
    def __init__(self, x=4):
        self.x = x

    def calculate_something(self, event):
        if x > 2:
           print("hello")

我通过以下方式初始化所有内容:

example = A(strat1)

初始化时,我需要能够将任意数量的参数传递给strat1类中的calculate_something方法,如下所示:

example = A(strat1, x=3)

example = A(strat1, x=3, y=5)

其中y将在calculate_something方法中进一步使用。

我该怎么做?我需要能够通过两个"新变量"并覆盖x变量。我曾多次尝试使用* args和** kwargs,但我最终会遇到错误。

1 个答案:

答案 0 :(得分:0)

以下是您的评论代码。重点是你必须在 A 中保存参数,并在初始化时将它们传递给 strat

class A(object):
    def __init__(self, strat, **strat_kwargs):
        self.strat_cls = strat
        # save kwargs to pass to strat
        self.strat_kwargs = strat_kwargs
        self._genInstances()

    def _genInstances(self):
        # init strat with kwargs
        self.strat = self.strat_cls(**self.strat_kwargs)


class strat1(Strat):
    def __init__(self, x=4, y=None):
        # save x and y
        self.x = x
        self.y = y

    def calculate_something(self, event):
        # use self.x here
        if self.x > 2:
            print("hello")
相关问题