3.1 Functions as First Class Objects
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
<strong>Functions</strong> <strong>as</strong> FCO<br />
Everything is an object
<strong>First</strong> Cl<strong>as</strong>s <strong>Objects</strong><br />
Python’s functions are first-cl<strong>as</strong>s objects. You can <strong>as</strong>sign them to<br />
variables, store them in data structures, p<strong>as</strong>s them <strong>as</strong> arguments to<br />
other functions, and even return them <strong>as</strong> values from other<br />
functions.
<strong>Functions</strong> are objects<br />
def yell(text):<br />
return text.upper() + '!'<br />
>>> yell('hello')<br />
'HELLO!'<br />
>>> bark = yell<br />
>>> bark('woof')<br />
'WOOF!'
<strong>Functions</strong> can be stored in Data Structures<br />
>>> funcs = [bark, str.lower,<br />
str.capitalize]<br />
>>> funcs<br />
[,<br />
,<br />
]<br />
>>> for f in funcs:<br />
... print(f, f('hey there'))<br />
'HEY<br />
THERE!'<br />
'hey<br />
there'<br />
'Hey there'
<strong>Functions</strong> can be p<strong>as</strong>sed to other functions<br />
>>> greet(yell)<br />
def greet(func):<br />
'HI, I AM A PYTHON PROGRAM!'<br />
greeting = func('Hi, I am a Python program')<br />
print(greeting)<br />
def whisper(text):<br />
return text.lower() + '...'<br />
>>> greet(whisper)<br />
'hi, i am a python program...'
<strong>Functions</strong> can be nested<br />
def speak(text):<br />
def whisper(t):<br />
return t.lower() + '...'<br />
return whisper(text)<br />
>>> speak('Hello, World')<br />
'hello, world...'<br />
>>> whisper('Yo')<br />
NameError: "name 'whisper' is not<br />
defined"<br />
>>> speak.whisper<br />
AttributeError: "'function' object<br />
h<strong>as</strong> no attribute 'whisper'"<br />
def get_speak_func(volume):<br />
def whisper(text):<br />
return text.lower() + '...'<br />
def yell(text):<br />
return text.upper() + '!'<br />
if volume > 0.5:<br />
return yell<br />
else:<br />
return whisper