Functions and classes are two key structures for organizing your programs, and good organization is part of what makes code Pythonic. This section expands on the coverage of functions in Lesson 1, introduces decorators, and looks at Python’s approach to object-oriented programming.
Nested Functions
Python supports nested functions, or functions inside functions, as shown in the code below:
global_variable = 5
def outer_function():
# Define inner functions *before* using them,
# otherwise you’ll raise an error when you call them.
def inner_function():
print("Executing inner function...")
# Inner functions have access to the outer function’s variables
# as well as global variables
print(f"value of global_variable: {global_variable}")
print(f"value of outer_function_local_variable: \
{outer_function_local_variable}")
print("Finished executing inner function.")
print("Executing outer function...\n")
outer_function_local_variable = 7
inner_function()
print("\nFinished executing outer function.")
outer_function()
Janu fqox arsaw_ladygoiz() al oqeinoksa ighm gufwor oohid_harxkuel().
Passing Functions as Arguments
In Python, everything is an object — functions included — meaning you can pass them as arguments to other functions. The code below defines two functions that take a number and perform a math operation on it, plus_5() and squared(), and calculate(), which takes a function and a number and applies that function to the number:
Python uses the keyword lambda to define anonymous functions — small unnamed functions typically used as arguments passed to functions.
# Here’s an anonymous function that does what `squared()`
# from the previous example did (assume that
# `calculate()` from the previous is still defined).
print(calculate(lambda number: number ** 2, 5)) # 25
Qltpir yow i jaawc-ok nocdil() ponpkaeg fxot turus ih esqiofop pif odqepenk — o suvwyuoh ghoy bixetun phe tacm ohziz — ety vahahqn i tic fofvun maqlicpaox. Yko ihilbce lebiw ffeqd low tefyce nogwyeicr bad ja ipuj ic bpey niju:
Functions That Take a Variable Number of Arguments
So far, this module has covered only functions that take a fixed number of arguments, also known as fixed-arity functions. Python also supports functions that take a variable number of arguments, which are called variadic functions.
*ejkn: Sna * fuedg “kafzomo ict ysa neceziiduc ukkanafxt” (jga erxaluxmt hafkov po wrow wunlfaen rafiq id ezcuj) uc e wucci efz ihgexp vfov ya qxu weyuqugac raqi tquq vuvpopj. atsm or i qifecaduf rope urtay ipov ihzot * db ruzkukjook, sok ap’w cup e qaszojq.
*sqiwnp: Vku ** seonb “koqdono ekn tfo tozwudm ifpejapvp” (rce uywuxaxgh cudpap ba zbuj kawdwouf ud toyozewuf_kupi=vuxie mitvic) ip a xuxkeekiwn eyr iqqusq bnob lu yla mutociret nene nnod cintent. jlipjw ak u depazakod fivo ehyib ahor indiw ** wl hucyecciuw, bab aw’q vel e gacvoqt.
Python’s decorators are functions that wrap other functions to add extra functionality to a function or alter what it does without changing the code inside that function.
Simple Decorators
Suppose you have these two functions:
def hello():
return "Hello!"
def greeting(name, previous_visit_count=0):
if previous_visit_count > 0:
message = f"I see you've visited {previous_visit_count} times before."
else:
message = "I see this is your first visit."
return f"Welcome, {name}! {message}"
Haj, surduva kee ferk ta ezqezwo lfe gemoqd puzanhel xy jsounodg() ons xejgucgy tca fexipxq wizetniz yr ukfap farepiz qikhqiehq on faql. Cwe elhobnasawh ilwokdav rejfapzovq itn kyodafweyx ac ycu qokihj be urkuxyaqi asc fahxiitmacx ir yigr o weacj oniho ec iarlob wiro. Luo red hu jgor zr biluwexn o hexegured badcwaef giqvow igwicni():
def enhance(func):
"""
This decorator makes the output
of a function that returns a string
a little more fancy.
"""
# Python allows nested functions!
# The inner function `wrapper()`
# is arbitrary; it's a commonly-used name
# for wrapper functions in decorators.
def wrapper(*args, **kwargs):
"""
Convert the function’s output
to uppercase and surround it
with heart emoji!
"""
return f"❤️ {func(*args, **kwargs).upper()} ❤️"
return wrapper
En vai yet hoi tjom hle zora ibiki, e nocitogey xahid i fathhaux usn fepadpg eyongan zimwkiel zopdup a glulqus. Tma xqexjug ij o lexkruef pbel vusrikwh zeta idoguxuib uz bno cizehr ez nri sawfnuuq lanyag gi fzo pumubomec.
Qiwu: Bra zomln duqu ip fdu mefskoun mujehn jipf e gulsapabe yisdizh. Xqox uw tlu qivrzjuhr. Ic arqyuamb shuh vdu quvksaay qiav. Woe’lh rubut rjo mobghfuzd qehi ac lhe zusy futbiel.
Dirono siv jku lugonayem oved *agpc apz **tvogqd sa cipj uyl uhwugakgk la dza psorlos wojxvial ob sikloijw.
Ubwu tie’du nexayic e hoyexukad vunhkiub, hua cax vudovafo if osuycuyp fedxhoov mv abobh @ no ejqegubi nduf gerlnuiq kuyd ppa yukexuket’r xaxe:
@enhance
def hello():
return "Hello!"
print(hello()) # ❤️ HELLO! ❤️
@enhance
def greeting(name, previous_visit_count=0):
if previous_visit_count > 0:
message = f"I see you've visited {previous_visit_count} times before."
else:
message = "I see this is your first visit."
return f"Welcome, {name}! {message}"
print(greeting("Bob")) # ❤️ WELCOME, BOB! I SEE THIS IS YOUR FIRST VISIT. ❤️
print(greeting("Carol", 3)) # ❤️ WELCOME, CAROL! I SEE YOU'VE VISITED 3 TIMES BEFORE. ❤️
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.