Function Objects¶
What’s a Function?¶
First: what’s a variable?
|
i = 1
|
Functions are no different …
|
def square(number):
"""
return square
of the argument
"""
return number**2
|
Function Objects?¶
square
is a name that happens to refer to a function object …
>>> square
<function square at 0x7fca2c785b70>
>>> square.__doc__
'\n return square\n\tof the argument\n\t'
>>> square(3)
9
Function Objects! (1)¶
>>> square = 1
>>> square(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
op = square
op(3)
Function Objects! (2)¶
def forall(op, list):
result = []
for elem in list:
result.append(op(elem))
return result
print(forall(square, [1, 2, 3]))
print(forall(len, ["Joerg", "Faschingbauer"]))
[1, 4, 9]
[5, 13]
Batteries included: Python built-in function map