I would like to do something like the following:
def add(a, b):
#some code
def subtract(a, b):
#some code
operations = [add, subtract]
operations[0]( 5,3)
operations[1](5,3)
In python, is it possible to assign something like a function pointer?
-
1Try actually executing that code in the interactive environment and see what happens.Robert Rossney– Robert Rossney2008年11月21日 01:27:44 +00:00Commented Nov 21, 2008 at 1:27
-
I'm tempted to delete the silly [function-pointer] and [anonymous-methods] tags because they don't makes sense in Python. But then, this kind of question shows that Python lacks those complexities.S.Lott– S.Lott2008年11月21日 02:22:27 +00:00Commented Nov 21, 2008 at 2:22
-
2you're in luck, my friend, but they're neither anonymous nor unboundJeremy Cantrell– Jeremy Cantrell2008年11月21日 02:42:28 +00:00Commented Nov 21, 2008 at 2:42
-
I think by "unbound functions" he meant "functions, not methods".tzot– tzot2008年11月21日 08:26:25 +00:00Commented Nov 21, 2008 at 8:26
-
No, "unbound functions" is a hair-splitting in C++ and "prothon" to explain functions that are not (yet) bound to a class, but could be. And Java folks have to give functions fancy-sounding names.S.Lott– S.Lott2008年11月21日 11:30:12 +00:00Commented Nov 21, 2008 at 11:30
3 Answers 3
Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.
Comments
Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value.
You can use this to implement a Strategy pattern, for example:
def the_simple_way(a, b):
# blah blah
def the_complicated_way(a, b):
# blah blah
def foo(way):
if way == 'complicated':
doit = the_complicated_way
else:
doit = the_simple_way
doit(a, b)
Or a lookup table:
def do_add(a, b):
return a+b
def do_sub(a, b):
return a-b
handlers = {
'add': do_add,
'sub': do_sub,
}
print handlers[op](a, b)
You can even grab a method bound to an object:
o = MyObject()
f = o.method
f(1, 2) # same as o.method(1, 2)
2 Comments
def foo(): ...; bar = foo then foo and bar are both names referring to a function. There is no difference between them. So if foo is a function, then why isn't bar a function?Just a quick note that most Python operators already have an equivalent function in the operator module.