Advanced Lesson 4
Python Decorators
Chapter 1: Introduction
Functions as first class objects
The second point to remember: everything is an object
in Python. That includes functions. So you can assign a function to a variable.
We have discussed this briefly in Core Lesson 10. Let’s see whether you remember this. Try to guess what the output is below, and verify your answer by running the code!
def do_math(x, y):
return x*y + 2**x
z = do_math
print(z(3, 4)) # What is printed here?
print(type(z)) # What is the type?
print(z) # What is z?
Note the difference between the code above and the one below. Make sure you understand the difference! The one above assigns z
to the function do_math
. The second assigns z
to the value returned after calling do_math()
.
z = do_math(3, 4)
print(type(z)) # What is the type?
print(z) # What is z?