code_junkie

anonymous unbound functions in python

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. def add(a, b):
  2. #some code
  3.  
  4. def subtract(a, b):
  5. #some code
  6.  
  7. operations = [add, subtract]
  8. operations[0]( 5,3)
  9. operations[1](5,3)
  10.  
  11. def the_simple_way(a, b):
  12. # blah blah
  13.  
  14. def the_complicated_way(a, b):
  15. # blah blah
  16.  
  17. def foo(way):
  18. if way == 'complicated':
  19. doit = the_complicated_way
  20. else:
  21. doit = the_simple_way
  22.  
  23. doit(a, b)
  24.  
  25. def do_add(a, b):
  26. return a+b
  27.  
  28. def do_sub(a, b):
  29. return a-b
  30.  
  31. handlers = {
  32. 'add': do_add,
  33. 'sub': do_sub,
  34. }
  35.  
  36. print handlers[op](a, b)
  37.  
  38. o = MyObject()
  39. f = o.method
  40. f(1, 2) # same as o.method(1, 2)
Add Comment
Please, Sign In to add comment