Chet
Chet

Reputation: 19829

How to pass a function as a parameter to a class in python

I want to pass a function to a class when I initialize it. Here's a toy example I came up with and it works:

def addition(self):
        return self.a + self.b


def multiplication(self):
    return self.a * self.b


class Test:

    def __init__(self, a, b, fcn):
        self.a = a
        self.b = b
        self.fcn = fcn

t = Test(3, 3, addition)

print t.fcn(t)

t = Test(3, 3, multiplication)

print t.fcn(t)

Is it possible to simply call t.fcn() as you would any other class method?

Upvotes: 1

Views: 99

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113930

did you try it?

the answer is yes

def do_op(x,y,fn):
   return fn(x,y)

def add(a,b):
   return a+b

print do_op(5,4,add)

same with a class

class whatever:
      def __init__(self,fn):
         self.fn = fn
      def do_it(self,*args,**kwargs):
         return self.fn(*args,**kwargs)
         #if you wanted the fn to have self as the first argument
         #return self.fn(self,*args,**kwargs) #just pass self as first argument

x = whatever(add)
print x.do_it(5,8)

further along what you are asking for (if im reading it right)

def add(self):
   return self.a + self.b

class whatever:
      def __init__(self,fn,a,b):
         self.__dict__[fn.__name__] = fn
         self.a,self.b = a,b
      def do_it(self):
         return self.fn(self)

x = whatever(add,6,7)
x.do_it()

or perhaps you want something like

from functools import partial
def add(self):
   return self.a + self.b
class whatever:
      def __init__(self,fn,a,b):
         self.__dict__[fn.__name__] = partial(fn,self)
         self.a,self.b = a,b

x = whatever(add,5,6)
x.add()

this kind of introspection is somewhat risky in deployed code ...

Upvotes: 4

Related Questions