Functions are First-Class Citizens
- everything is an object, this includes functions
- you can assign functions to variables,
- use them as arguments to other functions
- return them from functions
def answer():
print(42)
def run_something(func):
func()
run_something(answer)
# pass answer to run_something => using function as data
- You passed answer, not answer()
- without parathesis Python treats the function like any other object
type(run_something)
<class 'function'>
def add_args(arg1, arg2):
print(arg1 + arg2)
def run_something_with_args(func, arg1, arg2):
func(arg1, arg2)
# func - function to run
# arg1 - first argument for func
# arg2 - 2nd argument for func
Inner Functions
- you can define a function within another function
def outer (a,b):
def inner(c,d):
return c+d
return inner(a,b)
outer(4,7)
# Output
11
- usefull when performing some complect task more than once withoin another function, to vavoid loops or code duplication.
def knights (saying):
def inner(quote):
return "We are the knights who say: '%s'" %quote
return inner(saying)
knights ('Ni!')
# Output
We are the knights who say: Ni!
Closure
- inner function can function as closure
- This is a function that is dynamically generated by onother function and can both change and remember the values of variables that were created outside the function.
def knights2(saying):
def inner2():
return "We are the knights who say: '%s'" %quote
return inner2
knights ('Ni!')
# Output
We are the knights who say: Ni!
- The inner2() function knows the value of saying that was passed in and remembers it. The line return inner2 returns this specialized copy of innner2 function (but doesn’t call it). That’s a kind of closure: dynamically created function that remembers where it came from.
=> to do more research on this!