Python functional programming, just read this article!
This article provides a simple introduction to functional programming technology in Python.
First-class functions
In Python, functions are "first-class citizens". That is, functions are on an equal footing with other data types such as int.
Thus, we can assign functions to variables, pass them as arguments to other functions, store them in other data structures (such as dicts), and use them as return values of other functions.
Treat functions as objects
Since other data types (such as string, list, and int) are objects, then functions are also objects in Python. Let's look at the example function foo, which prints its own name:
1 2 |
|
Since functions are objects, we can assign function foo to any variable and then call that variable. For example, we can assign a function to the variable bar:
1 2 3 |
|
The statement bar = foo assigns the object referenced by the function foo to the variable bar.
Treating objects as functions
When objects are callable, they are the same as functions, such as object(). This is achieved through the __call__ method.
The example is as follows:
1 2 3 4 5 |
|
Every time we configure an object of the Greeter class, we will create a new object, which is a new name that can be shouted when greeting. As shown below:
1 2 3 |
|
The reason why we can call the morning object is that we have used the __call__ method in the class definition. To check if an object is callable, we use the built-in function callable:
1 2 |
|
Functions inside data structures
Functions, like other objects, can be stored inside data structures. For example, we can create a dictionary of int to func. This comes in handy when an int is a shorthand for the step to be performed.
1 2 3 4 5 6 7 |
|
Similarly, functions can be stored in a variety of other data structures.
Use functions as parameters and return values
Functions can also be used as parameters and return values of other functions. Functions that accept functions as input or return functions are called higher-order functions, and they are an important part of functional programming.
Higher-order functions have powerful capabilities. As explained in "Eloquent JavaScript":
- "Higher-order functions allow us to abstract actions, not just abstract values."
Let's take a look one example. Suppose we want to iterate over a list of items and print them out in sequence. We can easily build an iterate function:
1 2 3 |
|
It looks cool, but it’s just a first-level abstraction. What if we want to do something other than print while iterating over the list?
This is the meaning of the existence of higher-order functions. We can create a function iterate_custom, where the list to be iterated over and the function to be applied to each item are the inputs to the iterate_custom function:
1 2 3 |
|
This may seem trivial, but it is actually very powerful.
We have raised the level of abstraction to make the code more reusable. Now, not only can we call this function when printing a list, we can also perform arbitrary operations on the list involving sequence iteration.
Functions can also be returned, making things even simpler. Just like we store functions in dict, we can also use functions as control statements to determine the appropriate function. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Nested functions
Functions can also be inside other functions. This is an "internal function". Intrinsic functions are useful when creating helper functions, small reusable functions that serve as submodules to support the main function.
We can use auxiliary functions when the problem requires a specific function definition (parameter type or order). This non-traditional approach makes problem solving much simpler, see for example: http://www-inst.eecs.berkeley.edu/~cs61a/sp12/lectures/lect4-2x3.pdf.
Suppose you want to define a Fibonacci function fib(n), which has only one parameter n, and we must return the nth Fibonacci number.
One possible way to define such a function is to use a helper function to track the first two terms of the Fibonacci sequence (since the Fibonacci number is the sum of the first two numbers).
1 2 3 4 5 6 7 8 9 10 |
|
Move the calculation from the function body to the function parameters, which is very powerful. Because it reduces redundant calculations that may occur in recursive methods.
Single expression function (Lambda expression)
What should we do if we want to write a function before giving the function a name? What if we want to write a short one-line function (such as function foo or mult in the example above)?
We can use the lambda keyword in Python to define such functions. An example is as follows:
1 2 |
|
The mult function behaves the same as a function defined using the traditional def keyword.
Note: The lambda function must be a single line and cannot contain return statements written by the programmer.
事实上,它们通常具备隐式的返回语句(在上面的示例中,函数想表达 return x * y,不过我们省略了 lambda 函数中的显式返回语句)。
lambda 函数更加强大和精准,因为我们还可以构建匿名函数(即没有名称的函数):
1 |
|
当我们只需要一次性使用某函数时,这种方法非常方便。例如,当我们想填充字典时:
1 2 3 |
|
接下来我们来看 Map、Filter 和 Reduce,以更多地了解 lambda。
Map、Filter 和 Reduce
Map
map 函数基于指定过程(函数)将输入集转换为另一个集合。这类似于上文提到的 iterate_custom 函数。例如:
1 2 3 4 5 |
|
在 Python 3 中,map 函数返回的 map 对象可被类型转换为 list,以方便使用。现在,我们无需显式地定义 multiply_by_four 函数,而是定义 lambda 表达式:
1 |
|
当我们想对集合内的所有值执行某项操作时,map 函数很有用。
Filter
就像名称所显示的那样,filter 函数可以帮助筛除不想要的项。例如,我们想要去除 scores 中的奇数,那么我们可以使用 filter:
1 2 |
|
由于提供给 filter 的函数是逐个决定是否接受每一个项的,因此该函数必须返回 bool 值,且该函数必须是一元函数(即只使用一个输入参数)。
Reduce
reduce 函数用于「总结」或「概述」数据集。例如,如果我们想要计算所有分数的总和,就可以使用 reduce:
1 2 |
|
这要比写循环语句简单多了。注意:提供给 reduce 的函数需要两个参数:一个表示正在接受检查的项,另一个表示所用运算的累积结果。
本文是关于函数式编程的一篇入门文章,虽然尽量完备地介绍了相关的知识,但并不是那么深入。如想了解更多,大家可以阅读以下资源:
- Best Practices for Using Functional Programming in Python:https://kite.com/blog/python/functional-programming/
- Functional Programming Tutorials and Notes:https://www.hackerearth.com/zh/practice/python/functional-programming/functional-programming-1/tutorial/
The above is the detailed content of Python functional programming, just read this article!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.
