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


i want pass function class when initialize it. here's toy example came , 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 =         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 possible call t.fcn() other class method?

did try it?

the answer 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 class

class whatever:       def __init__(self,fn):          self.fn = fn       def do_it(self,*args,**kwargs):          return self.fn(*args,**kwargs)          #if wanted fn have self first argument          #return self.fn(self,*args,**kwargs) #just pass self first argument  x = whatever(add) print x.do_it(5,8) 

further along asking (if im reading 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 want 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 risky in deployed code ...


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -