jeudi 9 mai 2019

How to inject a central managed resource into constituent objects in Python

I have a class, let's call it foo:

class Foo:

    def __init__(self, attr_1, attr_2, managed_obj):
        self.attr_1 = attr_1
        self.attr_2 = attr_2
        self.managed_obj = managed_obj

and the object, managed_obj, is managed by another class:

class Controller:

    def __init__(self, *foos):
        self.managed_obj = ManagedObj(self)
        self.foos = [f(self.managed_obj) for f in foos]

Now, the flow of execution works such that Controller has some central supervision and control over Foo objects. However, each Foo needs to access the controller's managed_obj and I don't really want the user to have to pass that around. Currently, I have to build Controller by submitting a lambda for each Foo I want to generate, with an argument for managed_obj. I don't really like this implementation but I'm having trouble finding a better one.

Does anyone have any ideas?

Aucun commentaire:

Enregistrer un commentaire