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!
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
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
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.
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):
return a[2:]
new_str = func_7(my_str) #call built-in function
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.
**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
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