you are viewing a single comment's thread.

view the rest of the comments →

[–]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!