I'm wondering if there is an accepted way to pass functions as parameters to objects (i.e. to define methods of that object in the init block).
More specifically, how would one do this if the function depends on the objects parameters.
It seems pythonic enough to pass functions to objects, functions are objects like anything else:
def foo(a,b):
return a*b
class FooBar(object):
def __init__(self, func):
self.func = func
foobar = FooBar(foo)
foobar.func(5,6)
# 30
So that works, the problem shows up as soon as you introduce dependence on the object's other properties.
def foo1(self, b):
return self.a*b
class FooBar1(object):
def __init__(self, func, a):
self.a=a
self.func=func
# Now, if you try the following:
foobar1 = FooBar1(foo1,4)
foobar1.func(3)
# You'll get the following error:
# TypeError: foo0() missing 1 required positional argument: 'b'
This may simply violate some holy principles of OOP in python, in which case I'll just have to do something else, but it also seems like it might prove useful.
I've though of a few possible ways around this, and I'm wondering which (if any) is considered most acceptable.
Solution 1
foobar1.func(foobar1,3)
# 12
# seems ugly
Solution 2
class FooBar2(object):
def __init__(self, func, a):
self.a=a
self.func = lambda x: func(self, x)
# Actually the same as the above but now the dirty inner-workings are hidden away.
# This would not translate to functions with multiple arguments unless you do some ugly unpacking.
foobar2 = FooBar2(foo1, 7)
foobar2.func(3)
# 21
Any ideas would be appreciated!