简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM