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

 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:

 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:

 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)
        #  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)
 Copy code 

The above code is the functional implementation of summation , Some of the logic is as follows :

  1. 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 ;
  2. Pass in a judgment condition , In this case, it is a lambda expression , Used to judge 5 and 7 Multiple ;
  3. 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'>
 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 :

  1. No changes to global variables ;
  2. 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.

Random recommended