0

In my model I have a class containing a rather generic function, which calls a higher order function. I put together a simple example of it:

class AClass(object):

    def __init__(self, prop, fun):
        self.prop = prop
        self.fun = fun

    def do_sth(self):
        self.fun()

def namely_this_(context):
    print 2*context.prop

obj1 = AClass(3, namely_this_)
obj1.do_sth()

This snippet contains everything to know, just note, that it could be continued by something like:

def namely_this_2(self):
    print 4*self.prop
obj2 = AClass(2, namely_this_2)

obj2.do_sth()

The above code does not run, instead it throws a

TypeError: namely_this_() takes exactly 1 argument (0 given)

Instead, I have to change the do_sth to

    def do_sth(self):
        self.fun(self) # the *self* in the parenthesis added

Question: In what way does the namely_this_ differ from functions defined inside a class and is my workaround a viable solution?

Milla Well
  • 3,193
  • 3
  • 35
  • 50

1 Answers1

1

An instance method is a property of the class, not the instance itself. If you changed your init to assign fun to self.__class__.fun, it would work; except then of course all instances would share the same function, which is clearly not what you want.

In order to make it an actual method, you need to make it an instance of types.MethodType:

def __init__(self, prop, fun):
    self.prop = prop
    self.fun = types.MethodType(fun, self)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895