0

Can a function be used as a parameter of the python __init__ method?

What I'm trying to do is write a class for both the perceptron and logistic regression learning algorithms. As their training functions are very similar, and only really differ by the function used for prediction, it would be nice to be able to specify this function function at construction.

I hope this question hasn't been asked before (I've searched, haven't found anything; maybe I'm searching for the wrong topic). An example would be great. I'm not that familiar with lambda, so please provide some justification for any advanced python features. Thanks!

2 Answers 2

6

Yes. Functions are first-class objects in Python, so you can pass them into any function you like as a parameter, including __init__.

def a():
    print("Hello!")

def b(fun):
    print("running fun")
    fun()
    print("all done")

b(a) # prints "running fun", then "Hello!", then "all done".

You can store them in classes just like any other variable:

class c(object):
    def __init__(self, fun):
        self.fun = fun
        self.fun()

lambda is just another way of writing a function, without having to store it in a variable. It can be used for defining functions on the fly, for example:

def d(fun, num):
    return fun(num)

def e(x):
    return x**2

d(lambda x: x**2, 7) # Returns 49
d(e) # Also returns 49
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, functions are first-class objects, and can be passed around as arguments.

Short demo:

>>> def foo(): print 'foo!'
... 
>>> bar = foo
>>> bar()
foo!
>>> def ham(eggs):
...     eggs()
... 
>>> ham(bar)
foo!

Note how I assigned foo to a new name bar, then called it both from bar and passed it to another function, where the parameter egg is called as a function.

Lambdas are just a short-form notation to create function objects. From Python's perspective, there is little difference:

>>> baz = lambda: 'baz'
>>> baz()
'baz'
>>> baz
<function <lambda> at 0x10f15c7d0>
>>> foo
<function foo at 0x10f15c6e0>

Both the baz lambda and the preceding foo function are function objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.