mardi 19 octobre 2021

Python circumvent no access to self

I struggle with the following scenario in Python:

Let's say I have a secret method from which I know that it runs a loop and executes a given function returning a value in each iteration. I want to store the results of each iteration of the loop, but in the outside_fct I do not have access to the parameter self.collect_results, as the outside function takes no self parameter. Let's say I need to access self.collect_results to store the sub_results. As you see the outside_fct needs access to an internal parameter of the Routine class but as it does not know a specific instance of this class, it cannot store the results.

If the outside_fct would be inside the Routine class, it would have access to the self parameter. However, this is not the case. Does someone know a design pattern or strategy to register each result of the secret_method loop in the Routine class?

import secret_method # runs loop n times, calls passed function each round, do other secret things

def outside_fct(some_int: int):
    return random.randint(1, 10) + some_int

class Routine():

    def __init__(self):
        self.collect_results = []

    def handle_sub_result(self, sub_result):
        self.collect_results.append(sub_result)
        # want to get the result of each call of the secret_method loop

    def _start(self, f):
        result = secret_method(f)

routine = Routine()
routine._start(outside_fct)

Aucun commentaire:

Enregistrer un commentaire