current position:Home>Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
2022-01-29 20:19:20 【Dream eraser】
Little knowledge , Great challenge ! This article is participating in 「 A programmer must have a little knowledge 」 Creative activities
This article has participated in 「 Digging force Star Program 」 , Win a creative gift bag , Challenge creation incentive fund .
Snowballing Python The fourth round , This time we have to learn something difficult , therefore , Erasers will reduce the difficulty of reading and understanding , Try to use vernacular to pave the way for you .
Write it at the front
This round of learning , Very biased theory , Because some concepts involved are also the style of other programming languages , And there are some disputes in the actual landing
But learn more , There is always no harm .
Snowballing Python The fourth round , Mainly learn functional programming
Each article in this series 3000 Word left or right ( Include code ), So rest assured to enjoy , It will not increase the daily learning intensity
Snowball History Series , Completed 3 A column , Updating 1 A column , That is, in the third round of learning update , So far 21 piece ~, Since the third round is project practice , learn Django Go to , So the fourth round of concept classes starts synchronously .
Python Functional programming
Python Not a purely functional language , But you can use Python Do functional programming
Typical listening to you , If you listen to me , To put it bluntly Python With the characteristics of functional programming ,
so, You can borrow the design pattern and programming technology of functional language , Write code like functional programming
I usually boast at this time , Functional code comparison Simplicity and elegance ~
Okay , It's all boasted .
The above contents belong to the scope of reasoning , That's in Python What are the skill points suitable for functional programming
What are the discomfort points ?
Following 2 Just make an impression
- advantage : Generator Expressions , This will be mentioned again and again later , With many higher-order functions , for example
reduce
,map
,filter
Three giants . - shortcoming : No infinite recursion, etc ~
If you go to Baidu “ What is functional programming ”, Many places will give answers
Functional programming : Allows the function itself to be passed as an argument to another function , It also allows you to return a function .
with reason !
In fact, functional programming is Define the expression in the function and the method to implement the expression , To put it bluntly, it is to use functions to land your code .
It looks like nonsense , It also has a supplementary explanation , In functional programming, avoid state changes and use variable objects .
among Avoid state changes Focus on the assignment statement and how it changes state , So you're in functional programming , I won't see it global
,nolocal
The content such as .
Different ways of writing the same case , Show functional programming
Concepts and principles are relatively abstract , Let's talk less about concepts , Leave this to the future and summarize it yourself , Direct display of source code differences .
Calculation 1~100 Inside , Calculation 5 And 7 The sum of multiples of
Process oriented writing
count = 0
for num in range(1, 101):
if num % 5 == 0 or num % 7 == 0:
count += num
print(count)
Copy code
In process oriented writing , Logic runs from top to bottom , for example num
from 1 Count to 100, If the 5 Or right 7 Take remainder equal to 0, That means divisible , And then count
With the corresponding num
Add up , Get the last remainder .
This idea is purely process oriented , Usually when we learn programming , The first thing to learn is this kind of writing .
Object oriented writing
There are two ways of writing this kind , One is to use Python Built in list implementation , One is to declare a class to implement .
The first way to write it :
count = list()
for num in range(1, 101):
if num % 5 == 0 or num % 7 == 0:
count.append(num)
print(sum(count))
Copy code
In the above writing , Variable count
Make a statement list
, List objects , But sorting still seems to be the shadow of some procedural programming languages .
For example, the last sum(count)
The use of is a little strange , I can't see the shadow of object-oriented .
Next , Let's create a custom class , Carry out logical implementation .
class My_List_Sum(list):
def sum(self):
count = 0
for n in self:
count += n
return count
count = My_List_Sum()
for num in range(1, 101):
if num % 5 == 0 or num % 7 == 0:
count.append(num)
print(count.sum())
Copy code
The above code , We implemented a My_List_Sum
class , Let it inherit from list
, At this point you should understand ,list
It's just a class name , Then it is implemented inside the class sum
Method , Call the object's sum
Method , Perfect application of object-oriented writing .
Let's get to the point , Implementation of functional programming
Before formal preparation , Need to recall some basic knowledge , for example lambda
Add expressions and lists .
Judge a number as 5 perhaps 7 Multiple , lambda
It is written as follows :
multiple = lambda x: x % 5 == 0 or x % 7 == 0
a = multiple(3) # False
b = multiple(5) # True
c = multiple(7) # False
print(a, b, c)
Copy code
The list addition code is as follows :
print([1]+[2]) # [1,2]
Copy code
With the above , You can write a recursive function , Implement the corresponding logic , The description of the code has been added to the comment .
def tool(n: int, end: int, filter_func) -> list:
""" Returns a filtered list :param n: Starting value :param end: Termination value :param filter_func: Judging expressions """
# If the upper limit is reached , Return the empty list directly
if n == end: return []
# If the filtering conditions are met , Returns a list of this value and the next value
if filter_func(n):
return [n] + tool(n + 1, end, filter_func)
else:
# The filter conditions are not met , Directly return the next value
return tool(n + 1, end, filter_func)
# Test code
ret = tool(1, 101, lambda x: x % 5 == 0 or x % 7 == 0)
print(ret)
print(sum(ret))
Copy code
The above code is the functional implementation of summation , Some of the logic is as follows :
- Given the initial and upper values , When the value of the iteration is equal to the upper limit , Return to empty list , That is, the operation ends ;
- Pass in a judgment condition , In this case, it is a lambda expression , Used to judge 5 and 7 Multiple ;
- When the conditions are met , What's going on is addition + Iterative work , When the conditions are not met , Go straight to the next iteration .
Of course, there is also a way to write functional programming , The code is as follows :
print(sum(n for n in range(1, 101) if n % 5 == 0 or n % 7 == 0))
Copy code
The generator used here will be described later .
Python Features of functional programming
stay Python in , Functions are objects , For example, after declaring a function , You can call its properties .
The following code shows the properties of the function object , The rest can be tested by yourself .
def my_func(var1, var2, **kw):
return var1 + var2
print(type(my_func)) # <class 'function'>
print(my_func.__code__)
print(my_func.__dict__)
print(my_func.__code__.co_code)
print(my_func.__code__.co_filename)
print(my_func.__code__.co_argcount)
Copy code
Functional programming is efficient , One of the most important reasons is to delay the calculation , Also called lazy evaluation , These will be gradually expanded later , It's still time to accept the concept of impression .
Because functions are objects , That's why we have the definition of functional programming at the beginning of this article .
Functions can use other functions as arguments , Or return another function , So in the actual coding process , We will convert the function into... In other code “ object ”, So as to realize functional programming .
Next, let's get in touch with Python The concept and application of pure function in .
Pure function
Pure function is a concept , That is, let the function not affect the scope outside the function , That is, the scope is local .
Say something simple. , Is to avoid assignment operations inside functions , It's similar, of course global
Keywords such as... Are also avoided .
For this purpose ,lambda
Expressions are pure functions .
First look at an example of a pure function :
def my_func(num: int) -> int:
return num * 100
Copy code
The return value of the function in the above code is only related to num
of , The following two conditions are satisfied :
- No changes to global variables ;
- The variable data structure was not updated , For example, a list of , Dictionaries .
After touching the concept of pure function , Let's take a look at the application of functions as objects .
stay Python Declare a class in , Some built-in methods will be carried by default , for example :
from typing import Callable
# Declare a class , This class is meaningless , Test use only
class Ext:
# Function passed in , It's portable 1~2 Parameters
def __init__(self, test_demo: Callable[[int], int]) -> None:
self.func = test_demo
# The returned result is expanded 2 times
def __call__(self, arg: int) -> int:
return self.func(arg) * 2
def one_func(var):
return var + 1
def two_func(var):
return var * 3
def three_func(var):
return var
a = Ext(one_func)
print(a(3)) # 8
b = Ext(two_func)
print(b(3)) # 18
c = Ext(three_func)
print(c(3)) # 6
Copy code
The above code uses a new module typing
, The module is Python 3.5 After that, the new module , Mainly for Python Provides static type checking .
In this case, the callback function is imported Callable
, The format is as follows :
Callable[[Arg1Type, Arg2Type],ReturnType]
Copy code
Where the inner square brackets Arg1Type
Is a parameter type ,ReturnType
Is the return value type .
The signatures of the above three functions are related to Callable
Consistency of definition , So it can be used as test_demo
The value of the parameter is passed .
Written in the back
Snowballing Python The fourth round , A very theoretical series , Keep up with the rhythm of the big army , Walk up , Any questions , You can leave a message in the comment area , commonly 1 It can be solved in an hour .
copyright notice
author[Dream eraser],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201292019187525.html
The sidebar is recommended
- Compile D + +, and use d to call C from python
- Install tensorflow and python 3.6 in Windows 7
- Python collects and monitors system data -- psutil
- Python collects and monitors system data -- psutil
- Finally, this Python import guide has been sorted out. Look!
- Quickly build Django blog based on function calculation
- Getting started with Python - object oriented - special methods
- Teach you how to use Python to transform an alien invasion game
- You can easily get started with Excel. Python data analysis package pandas (VI): sorting
- Implementation of top-level design pattern in Python
guess what you like
-
Using linear systems in python with scipy.linalg
-
Python tiktok 5000+ V, and found that everyone love this video.
-
Using linear systems in python with scipy.linalg
-
How to get started quickly? How to learn Python
-
Modifying Python environment with Mac OS security
-
You can easily get started with Excel. Python data analysis package pandas (XI): segment matching
-
Advanced practical case: Javascript confusion of Python anti crawling
-
Better use atom to support jupyter based Python development
-
Better use atom to support jupyter based Python development
-
Fast power modulus Python implementation of large numbers
Random recommended
- Python architects recommend the book "Python programmer's Guide" which must be read by self-study Python architects. You are welcome to take it away
- Decoding the verification code of Taobao slider with Python + selenium, the road of information security
- Python game development, pyGame module, python implementation of skiing games
- This paper clarifies the chaotic switching operation and elegant derivation of Python
- You can easily get started with Excel. Python data analysis package pandas (3): making score bar
- Test Development: self study Dubbo + Python experience summary and sharing
- Python + selenium automated test: page object mode
- You can easily get started with Excel. Python data analysis package pandas (IV): any grouping score bar
- Opencv skills | saving pictures in common formats as transparent background pictures (with Python source code) - teach you to easily make logo
- You can easily get started with Excel. Python data analysis package pandas (V): duplicate value processing
- Python ThreadPoolExecutor restrictions_ work_ Queue size
- Python generates and deploys verification codes with one click (Django)
- With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~
- At the beginning of "Python", you must see the series. 10000 words are only for you. It is recommended to like the collection ~
- [Python kaggle] pandas basic exercises in machine learning series (6)
- Using linear systems in python with scipy.linalg
- The founder of pandas teaches you how to use Python for data analysis (mind mapping)
- Using Python to realize national second-hand housing data capture + map display
- Python image processing, automatic generation of GIF dynamic pictures
- Pandas advanced tutorial: time processing
- How to make Python run faster? Six tips!
- Django: use of elastic search search system
- Fundamentals of Python I
- Python code reading (chapter 35): fully (deeply) expand nested lists
- Python 3.10 official release
- Solution of no Python 3.9 installation was detected when uninstalling Python
- This pandas exercise must be successfully won
- [Python homework] coupling network information dissemination
- Python application software development tool - tkinterdesigner v1.0 5.1 release!
- [Python development tool Tkinter designer]: Lecture 2: introduction to Tkinter designer's example project
- [algorithm learning] sword finger offer 64 Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
- leetcode 58. Length of Last Word(python)
- Problems encountered in writing the HTML content of articles into the database during the development of Django blog
- leetcode 1261. Find Elements in a Contaminated Binary Tree(python)
- [algorithm learning] 1486 Array XOR operation (Java / C / C + + / Python / go / trust)
- Understand Python's built-in function and add a print function yourself
- Python implements JS encryption algorithm in thousands of music websites
- leetcode 35. Search Insert Position(python)
- leetcode 1829. Maximum XOR for Each Query(python)
- [introduction to Python visualization]: 12 small examples of complete data visualization, taking you to play with visualization ~