Search code examples
pythonpython-2.7python-3.xkeyword-argument

Pass arbitrary number of variables through multiple functions/classes/methods


I have a class with methods that looks something like this

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)

and the strat_cls:

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

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

I initialize everything by:

example = A(strat1)

When initializing I need to be able to pass an arbitrary number of arguments to the calculate_something method in the strat1 class like this:

example = A(strat1, x=3)

or

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

where y will then be used further down in the calculate_something method.

How do I do that? I need to be able to pass both "new variables" and overriding the x variable. I've tried several times using *args and **kwargs, but I end up with errors.


Solution

  • Here is your code with comments. The main point is you have to save the arguments in A and pass them to strat when you're initializing it.

    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")