Consolidate the foundation of Python(5)

Consolidate the Python foundation
Five, function

Functions play an important role in Python. In addition to increasing code reusability, encapsulated functions have greater flexibility in the application of functions in Python. Whether you can make good use of functions may become an important indicator of whether you are a true Python master.

(1) Function, first is an object

First of all, Python is not only a dynamically strongly typed language, it is also a truly strongly typed language. Everything in python is an object, not just to talk about it. Constants are objects, variables are objects, and the four data structures are also objects (do you remember that they can be nested into each other?), then, what about functions? Yes, functions are also objects.

**Example 1: **Create a function to calculate the length of a string

def func_1(strs):

return len(strs)

func_1("How are you!")

12

As a Python object, it usually has three necessary attributes of the object model, namely id, type, and value. Let's take a look at the id, type, and value of the above function:

id(func_1)

47027880

type(func_1)

< class 'function'>

func_1

< function func_1 at 0x02CD96A8>

As a strong object type, it usually has the following characteristics:

And these features are available in Python functions.

1、 Function allows assignment to a variable

func_2 = func_1

PS: Please note that when a function is assigned to another variable, it will not be called, it is just a new name bound to the function object.

func_2("what’s this?")

12

Of course, since just adding a reference to the object, in fact, as long as your program needs, you can add more references, but you add more references. In essence, these variables all point to the same one Function object.

func_3 = func_1

if func_3 == func_2 : print(‘ok!’)

ok!

2、 Functions can be added as elements to other container objects

There are many container objects, such as lists, dictionaries, dicts, collections, etc. They can store any object, including integers and strings. Similarly, functions can also be stored in container objects. E.g

**Example 2: **The function is contained in a list as an independent element

list1 = [func_1, len]

for x in list1:

print(x("abcde"))

5

5

**Code analysis: **

(1) Two elements of list1: func_1 is our custom function, and len is a built-in function of python.

(2) For loop iteration, the function object is assigned to the x variable.

(3) Call x("abcde") and display it.

Of course, a more direct method is to get the function object through the index of the element, and then call the function.

list10

5

3、 Functions are allowed to be passed as arguments to another function

**Example 3: **

def func_4(func):

ln = func("The magic function of the function!")

print ("The length of the string is:" + ln)

func_4(func_1)

The length of the string is: 7

4、 A function is allowed as the return value of another function

Function as the return value of another function, for example:

def func_5():

return func_1

my_func = func_5()

my_func("my_python")

9

Can be abbreviated as:

func_5()("my_python")

9

Here, func_5 is actually a higher-order function. (What is a higher-order function? I suggest you read the book!)

PS: Among the Python built-in functions, typical higher-order functions such as map functions.

**Example: **map accepts a function and an iteration object as parameters. When calling map, iteratively calls the function with the elements of the iteration object as parameters.

map(func_1, ["abcde","def","gh","lmnopqr"])

lens = map(func_1, ["abc","def","gh","lmnop"])

list(lens)

[5, 3, 2, 7]

The function of map is equivalent to:

[ func_1(i) for i in ["abc","def","gh","lmnop"]]

[5, 3, 2, 7]

In comparison, the running efficiency of map will be faster.

(2) Functions can also be nested

The list contains the list, and the dictionary contains the dictionary. So, can the function contain the function? The answer is yes, this kind of function that contains functions is called nested function.

**Example 4: ** After removing the first 2 characters of the string, calculate its length

def func_6(my_str):

def func_7(a):

Get the slice with the first character removed

return a[2:]

new_str = func_7(my_str) #call built-in function

Calculate the length of the sliced string

return len(new_str)

func_6("i_python")

6

PS: It should be noted that the function located in the nested function is equivalent to a local variable, and its scope is limited to the inside of the nested function and cannot be accessed outside the function.

(3) How to create a class that can be called like a function

Implement the call method to be called!

**Example 5: ** Create a class that can be called

class get_sum:

def init(self, x):

self.x = x

def call(self, y):

return self.x + y

my_sum = get_sum(1) #Assign initial value

my_sum(5) #Call a custom class

6

Executing my_sum (5) is equivalent to calling get_sum.call_(self, 4), self is the instance object get_sum, and the initial value self.x is equal to 1, so the return value of calling my_sum (5) is 1 + 5

**PS: To determine whether an object is a callable object, you can use the built-in function callable to judge. **

callable(func_1)

True

callable(3)

False

callable(len)

True

all in all

Don’t just treat functions as functions,

It is not just a encapsulated code block,

It is also an object,

It can be like all other objects,

Be included, assigned, passed, returned,

It can also be nested,

Can be imitated. (And it's high imitation~!)

When you look at the function so thoroughly,

When it can still be used like this (666~),

It's hard for you not to be a great man!

statement:

This article is excerpted from an article by Yang Guo from the blog garden,

https://www.cnblogs.com/duex/p/6725694.html

(Partially modified)

Recommended Posts

Consolidate the foundation of Python(7)
Consolidate the foundation of Python(6)
Consolidate the foundation of Python(5)
Consolidate the foundation of Python (3)
Consolidate the Python foundation (2)
&quot;Consolidating the Foundation of Python&quot; (1)
The usage of wheel in python
Python handles the 4 wheels of Chinese
Python simulation of the landlord deal
What is the use of Python
The premise of Python string pooling
Secrets of the new features of Python 3.8
The father of Python joins Microsoft
The operation of python access hdfs
The usage of tuples in python
End the method of running python
Understanding the meaning of rb in python
Can Python implement the structure of the stack?
What are the required parameters of python
Logistic regression at the bottom of python
The usage of Ajax in Python3 crawler
Python solves the Tower of Hanoi game
Solve the conflict of multiple versions of python
7 features of Python3.9
What is the scope of python variables
Python implements the sum of fractional sequences
Two days of learning the basics of Python
What is the id function of python
Where is the pip path of python3
The essence of Python language: Itertools library
2.3 Python language foundation
What are the advantages of python language
The specific method of python instantiation object
2.1 The Python Interpreter (python interpreter)
python3 realizes the function of mask drawing
What is the prospect of python development
What is the function body of python
The specific method of python import library
Solve the conflict of multiple versions of python
What is the function of adb in python
Detailed explanation of the principle of Python super() method
The difference between the syntax of java and python
Python realizes the development of student management system
Python implements the shuffling of the cards in Doudizhu
The meaning and usage of lists in python
Solve the problem of python running startup error
Can the value of the python dictionary be modified?
Python implements the source code of the snake game
Detailed explanation of the usage of Python decimal module
How about learning python at the age of 27?
The consequences of uninstalling python in ubuntu, very
Python writes the game implementation of fishing master
Basics of Python syntax
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
09. Common modules of Python3
[898] python get the intersection of two lists | union | difference
Detailed explanation of the principle of Python function parameter classification
What is the advantage of python over corporate language
A brief summary of the difference between Python2 and Python3