Functional programming is not only use functions.
Think of “y = f(x)” or “h = f * g”
For comparasion, there are different paradigms in programming.
- Structured/Procedural – Functions, loops, conditions
- Object-Oriented Programming (OOP) – Classes, objects, methods
- Functional Programming – Decorators, comprehensions, and generators
- Logic Programming
Functions in Python are
first class value. It can take functions as arguments and return functions like a value.
In Python, there have anonymous functions which is called
Lambda Expression which’s body is limited to one expression.
Here, lambda expression used as a argument which is passed into function
calc. Function like
sub, they are too short and don’t need a special name to be identified. So, Python support a mechanism – anonymous function which is called
There is a another demo. We will change the code from procedure oriented into functional style.
filter is a related idea in functional tools like map.
filter return a new sequence where values are taken from the given sequence if they return True when passed to a given function.
reduce will accumulate and return a single result, given a sequence
and passing each value to a function along with the current result.
In Python, function is first-class value and can be used as returned value.
So, programmer can define nested functions in Python like this:
Look the demo below there.
Actually, the reture value of
wrapper is a function just little different from the original function passed into
wrapper like a shell on the original function and return with a more powerful function. That’s decorator.
wrapper is a decorator.
Decorator: A decorator is any callable Python object that is used to modify a function, method or class definition. A decorator is passed th original object being defined and returns a modified object, which is then bound to the name in the definition. Python decorators were inspired in part by Java annotations, and have a similar syntax; teh decorator syntax is pure syntactic sugar, using @ as the keyword – Wikipedia
Here is a more generic decorators
A better and more detailed explaination reader could read the blog
Understanding Python Decoratos in 12 Easy Steps!
which is written by
generator is a special type of iterator(not vice versa!).
Generator is a factory that lazily produces values.
There are two types of generators in Python: generator functions and generator expression.
Photo by Jason Leaster in ChangDe, HuNan, China.
What a big banana :)
作者: Jason Leaster
本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可