Process Oriented Object Oriented and Functional Analysis of Python Functional Programming

  • 2021-11-30 00:54:54
  • OfStack

The catalogue Python functional programming is different from the case, showing the process-oriented writing of functional programming and the object-oriented writing. Next, the landing of functional programming realizes the characteristics of Python functional programming. Pure function

Python Functional Programming

Python is not a purely functional language, but you can use Python for functional programming

Typical listening to one seat, such as listening to one seat, to put it bluntly, Python has the characteristics of functional programming,

so can borrow the design pattern and programming technology of functional language to write the code as functional programming

At this time, I will brag about 1. Functional code is simpler and more elegant ~

Well, it's over.

All of the above are within the scope of reasoning, which skills are suitable for functional programming in Python

What are the discomfort points?

Just make an impression on the following two points

Advantages: Generator expressions, which I'll talk about again and again, have many high-order functions, such as reduce , map , filter Big 3.

Disadvantages: There is no infinite recursion, etc. ~

If you go to Baidu "What is functional programming", many places will give the answer

Functional programming: Allows a function itself to be passed as an argument to another function, and also allows a function to be returned.

Makes sense!

In fact, functional programming is to define expressions in functions and achieve expressions for job hunting. To put it bluntly, it is to use functions to land your code.

Looks like nonsense, and it has a supplementary explanation for avoiding state changes and using mutable objects in functional programming.

Avoiding state change focuses on the assignment statement and how it changes state, so you won't see it in functional programming global , nolocal And so on.

Different writing methods of the same case show functional programming

Concepts and principles are more abstract, I still talk less about the concept, this left to your own summary in the future, and directly show the source code differences.

Calculate the sum of multiples of 5 and 7 within 1 ~ 100

Process-oriented writing


count = 0
for num in range(1, 101):
    if num % 5 == 0 or num % 7 == 0:
        count += num
print(count)

In process-oriented writing, logic runs from top to bottom, for example num Count from 1 to 100, and if the remainder of 5 or 7 equals 0, it means divisible, and then set count With the corresponding num Add it up to get the final remainder.

This kind of thinking is purely process-oriented writing. When we learn programming, the first thing we learn is this kind of writing.

Object-oriented writing

There are two ways to write this class, one is to use the built-in list of Python, and the other is to declare a class to achieve it.

The first way of writing:


count = list()
for num in range(1, 101):
    if num % 5 == 0 or num % 7 == 0:
        count.append(num)
print(sum(count))

In the above writing, the variable count Declare 1 list List objects, but collation still looks like a shadow of a procedural programming language.

For example, the last map0 The use of is a bit strange, and you can't see the shadow of object-oriented.

Next, let's create a custom class and implement it logically.


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())

The above code, we have implemented 1 by ourselves My_List_Sum Class, so that it inherits from the list At this time, you should understand, list Is a class name, and then implements it inside the class sum Method of the object, and then call the sum Method, the perfect application of object-oriented writing.

Next, let's get down to business, and realize the landing of functional programming

Before writing, you need to recall 1 basic knowledge, such as lambda Expressions and lists.

Determine that a number is a multiple of 5 or 7, 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)

The list addition code is as follows:


print([1]+[2]) # [1,2]

With the above, you can write a recursive function to implement the corresponding logic, and the description of the code has been added to the comments.


def tool(n: int, end: int, filter_func) -> list:
    """ Return 1 Filtered list 
    :param n:  Initial value 
    :param end:  Termination value 
    :param filter_func:  Judgment expression 
    """
    #  If the upper limit is reached, the empty list will be returned directly 
    if n == end: return []
    #  If the filter criteria are met, the value is the same as the following 1 A list of values 
    if filter_func(n):
        return [n] + tool(n + 1, end, filter_func)
    else:
        #  If the filtering criteria are not met, return directly to 1 Values 
        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))

The above code is a functional implementation of summation, and part of the logic is as follows:

Given the initial value and the upper limit value, when the iterative value is equal to the upper limit value, the empty list is returned, that is, the run is finished; Pass in a judgment condition, in this case, an lambda expression, which is used to judge the multiples of 5 and 7; When the conditions are met, the work of addition + iteration is carried out, and when the conditions are not met, the next iteration is directly entered.

Of course, there is also a functional programming method, the code is as follows:


print(sum(n for n in range(1, 101) if n % 5 == 0 or n % 7 == 0))

The generators used here will be described later.

Features of Python Functional Programming

In Python, a function is an object. For example, after declaring a function, you can call its properties.

The following code shows the properties of the function object, and the rest can be tested by itself.


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)

One of the most important reasons why functional programming is efficient is delayed calculation, also known as lazy evaluation, which will be gradually developed later, and now it is still the concept of receiving 1 impression.

It is precisely because functions are objects that we have the definition of functional programming in the opening paragraph of this article.

Functions can take other functions as arguments or return another function, so in the actual coding process, we will convert functions into "objects" in other codes, thus realizing functional programming.

Next, we will contact the concept and application of pure function in Python under 1.

Pure function

Pure function is a concept, which means that the function will not affect the scope outside the function, that is, the scope is local.

To put it simply, it is to avoid assignment operation inside the function, which is of course similar global And other keywords are also avoided.

In view of this, lambda Expressions are pure functions.

First, look at an example of a pure function:


def my_func(num: int) -> int:
    return num * 100

The return value of the function in the above code is only the same as that of the num The following two conditions are met:

Global variables are not changed; Variable data structures, such as lists and dictionaries, are not updated.

After touching the concept of pure function, let's understand the landing application of function as object under 1.

Declare a class in Python that by default carries some of the built-in methods, such as:


from typing import Callable
#  Declaration 1 Class, which is meaningless and only tests the use of 
class Ext:
    #  The passed-in function can carry the 1~2 Parameters 
    def __init__(self, test_demo: Callable[[int], int]) -> None:
        self.func = test_demo
    #  Return result expansion 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

The above code uses a new module typing This module is a new module after Python 3.5, which mainly provides static type inspection for Python.

In this case, the callback function is imported Callable The format is as follows:


count = list()
for num in range(1, 101):
    if num % 5 == 0 or num % 7 == 0:
        count.append(num)
print(sum(count))
0

With inner brackets Arg1Type Is the parameter type, ReturnType Is the return value type.

The signatures of the above three functions are the same as those of the Callable 1 defined, so it can all be used as test_demo Parameter to pass the value of the.

The above is Python functional programming process-oriented object-oriented and functional analysis of the detailed content, more about Python functional programming process-oriented object-oriented and functional information please pay attention to other related articles on this site!


Related articles: