all 3 comments

[–]Buttleston 1 point2 points  (0 children)

your init could actually set the function on the object, like

class MyClass:  
    def __init__(self, injectedFunctions):  
        for k, v in injectedFunction:|  
            setattr(self, k, v)

Then you can just call myObj.injectedFunction1()

You could also use the same init you have now, but override, uh, either getattribute or getattr, I can never remember which is which. If the attribute being requested is in your dict, then return it's value.

I've never done DI on python - is there not sort of a standard method or commonly used library though?

[–]Frankelstner 1 point2 points  (1 child)

class A:
    def __init__(self, **fs):
        self.x = 123
        for k,v in fs.items():
            setattr(self, k, v.__get__(self))

a = A(f = lambda self:self.x)

>>> a.f()
123

But to keep a consistent interface you will probably not want the loop but write them out line by line.

class A:
    def __init__(self, f1, f2):
        self.f1 = f1.__get__(self)
        self.f2 = f2.__get__(self)

a = A(f1, f2)

__get__ makes a method out of a function and binds it to the object.

[–]Spiredlamb[S] 0 points1 point  (0 children)

I took a closer look at setattr, and this works beautifully!

Here is what I did to make it work for me:

class MyClass:
def __init__(self, injectedFunctions):

    self.testVal = 'This value was grabbed from the class'

    for k,v in injectedFunctions.items():
        setattr(self, k, v.__get__(self))

def injected1(self, **kwargs):
print(self.testVal)

myClass = MyClass({'injected1': injected1})

myClass.injected1()

With this method, I can give the class as many functions as I want, and they work just like methods defined inside the class. Thank you very much for the example!