# - compatibility with Python 3
from __future__ import print_function # print('me') instead of print 'me'
from __future__ import division # 1/2 == 0.5, not 0
If I make a string in Python:
name = 'Matthew'
then I have a Python object of type str
:
type(name)
str
Let's say I defined a function add
:
def add(a, b):
return a + b
Now I have another Python object, of type function
:
type(add)
function
With my string, I can refer to the same string object, with a different variable name:
prisoner = name
prisoner
'Matthew'
It's the same for functions, because they are objects too:
my_add = add
type(my_add)
function
Functions are objects you can "call" by following the function object name with parentheses and arguments you want to pass:
add(1, 2)
3
my_add(1, 2)
3
As for any other object in Python, you can pass function objects to other functions:
def run_a_func(func, arg1, arg2):
result = func(arg1, arg2)
print('Result was', result)
run_a_func(add, 1, 2)
Result was 3
run_a_func(my_add, 1, 2)
Result was 3
def sub(a, b):
return a - b
run_a_func(sub, 1, 2)
Result was -1