By functions being first-class objects, we mean that we can:
- assign functions to variables
- store functions in data structures
- pass functions as arguments to other functions
- return functions as values from other functions.
Assignment
def yell(text):
return text.upper() + '!'
bark = yell
bark('woof')
Functions can be stored in data structures
funcs = [str.lower, str.capitalize]
for f in funcs:
print(f('hey there'))
Functions can be passed to other functions
def yell(text):
return text.upper() + '!'
map(yell, ['hello', 'hey', 'hi'])
Functions can be returned from other functions
def talk(volume):
def whisper(text):
return text.lower() + '...'
def yell(text):
return text.upper() + '!'
if volume > 0.5:
return yell
else:
return whisper
talk(0.8)("hello")
Top comments (0)