vendredi 6 mars 2020

What is the most pythonic way of sharing parameters between class methods

I have such a structure:

class Solver:
    def __init__(self, p1, p2, p3):
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3
        self.another_val = p3**p2

    def method_a(self, list_1, list_2):
        # do sth on these two lists


    def method_b(self, list_1, list_2, list_3):
        # do sth on these there lists

    def main_method(self):
        # construct list_1 here
        # construct list_2 here

        self.method_a(list_1, list_2)

        # construct list_3 here

        self.method_b(list_1, list_2, list_3)

    def iterator_method(self):
        # construct list_1 here
        # construct list_2 here
        for i in range(n):
            self.method_a(list_1, list_2)

Edit: A brief info what does this Solver class do: It basically solves a vehicle routing problem which the path of the problem file passed to its constructor. So the object holds some problem definitions (such as some matrixes or constants etc..) as object attributes. The Solver class is roughly defined above.

And these lists are just python lists and that means they are mutable. In this case:

  1. In the main_method(), should I pass list_1 and list_2 as parameters to the method_a() (as written in the above sample code), or should I not pass these parameters as method_a() can already reach them as they are? It's obvious that If I prefer the last one then I won't need to define list_1 and list_2 as parameters while defining method_a().

  2. Should I modify method_a() to return the list_1 and list_2 and assign them again to their corresponding values in the main_method() or it is better to leave them as it's in the sample code above?

  3. (redundant question) And again, should I pass list_1, list_2 and list_3 explicitly as parameters to the method_b() or not?

Note that, I call/use method_a() in other methods so I cannot merge these two (method_a() and method_b()) methods into one.

What is the most pythonic way of doing this? Or do you suggest any other patterns for such a case? I want to keep the code clean as much as possible.

Thanks!

Aucun commentaire:

Enregistrer un commentaire