This is the lecture note of CS61A - Lecture 7.
Exam Preview
Question 4: Implementing Function
1 | def remove(n, digit): |
Try it for yourself before looking at the answer.
1 | # ANSWER |
Decorators
Let's look at an example.
1 | def trace(fn): |
trace()
is a HOF. We have already learnt HOFs, so it's easy for us to understand the code.
However, if a programmer doesn't know HOFs, he/she won't understand the code. For those programmers who know nothing about HOFs, Python provides special syntax to apply higher-order functions as part of executing a def statement, called a decorator.
1 |
|
The annotation @trace affects the execution rule of def.
The function triple
will be created as usual. however, the name triple
is not bound to this function body. Instead, it is bound to the returned function value of calling trace
on the newly defined triple
function, i.e. triple = trace(triple)
.