Function basis
1. Function understanding
Function is a bunch of prepared code, call this bunch of code when needed
2. Function definition
def function name (parameter):
function body
3. Function return value
Return and yield are used to return. If there is no return value, the default return value is None.
return: What is returned is what is returned. Under normal circumstances, a function executes a return. The focus is on
yield: what is returned is a generator object.
The call method of multiple generators used when learning crawler framework :
1. Use next();
2. Use for...in loop
4. Function call
Function name (actual parameter) is a
good demonstration of the most basic function definition and call:
def make_love(a,b):
print(f'{a}和{b}陷入了爱河')
make_love('小明','小花')# '小明和小花陷入了爱河'
# 这是没有返回值的,用一个变量去接它,再打印显示的是None
b = make_love(1,2)# 注意赋值的时候,函数就调用了,所以会打印'1和2陷入了爱河'
# 而打印b时就只会打印返回值
print(b) # None
# 要是上面的不好理解,就看这个
def mysum(a,b):
print(a+22)
return a+b
s = mysum(1,2) # 23
print(s)# 3
5. Local variables and global variables
Global variables: It can be understood that variables defined outside the function can be accessed in the entire py file;
local variables: variables defined in the function can only be used within the function;
Note: If the local variable and the global variable have the same name, they will be Define a new local variable
inside the function instead of modifying the global variable; if you want to modify the global variable inside the function, use global to declare the variable, and you can modify the value of the global variable through the function;
built-in functions globals(), locals() can View global variables and local variables
a = 100
word = '你好
def test():
x = 'hello'
print('x = {}'.format(x))
a = 10
print('函数内部a = {}'.format(a))
global word
word = 'ok'
test()# x = hello
# 函数内部a = 10
# 打印函数内定义的变量,会报错
# print(x) # NameError: name 'x' is not defined
print('函数外部a = {}'.format(a))# 函数外部a = 100 这里a的值没有改变
print('函数外部word = {}'.format(word))# 函数外部word = ok 这里word的值改变了
# print('locals={},globals={}'.format(locals(), globals()))
6. Use of default parameters
def say_hello(a, b, c='湖南'):
print('我叫{},我今年{}岁,我来自{}'.format(a, b, c))
say_hello('张三', 18) # 没有传递参数,就使用默认值湖南
say_hello('张三', 18, '湖北') # 传递了参数,就使用传递的实参
7. Variable parameters
*args means variable positional parameters, positional parameters without =; **kwargs means variable keyword parameters, keyword parameters with =; args and kwargs can be replaced with other variable names, but it is recommended not to change the code When
calling a function to pass parameters: the
extra positional parameters will be stored in args in the form of tuples; the
extra keyword parameters will be stored in kwargs in the form of a dictionary;
def my_add(a, b, *args, **kwargs):
print('a={},b={},c={},kwargs={}'.format(a, b, args, kwargs))
c = a + b
for arg in args:
c += arg
return c
x = my_add(1, 2, x=1)# a=1,b=2,c=(),kwargs={'x': 1}
print(x)# 3
y = my_add(1, 3, 2, x=1, y=2)# a=1,b=3,c=(2,),kwargs={'x': 1, 'y': 2}
print(y)# 6
z = my_add(2, 2, 3, 4) # a=2,b=2,c=(3, 4),kwargs={}
print(z)# 11
8. Use of anonymous functions
In addition to using the keyword def to define a function, we can also use lambda expressions to define functions:
used to express a simple function, the number of times the function is called is few, basically only called once
. There are two ways to call an anonymous function:
1. Give He defines a name (used rarely)
2. Pass this function as a parameter to another function (used in more scenarios)
I use it when sorting the dictionary list
1.filter class
filter is to filter the iterable object, and get a filter object;
Python2 is a built-in function, Python3 is modified to a built-in class;
filter can be given two parameters, the first parameter is a function, and the second parameter is Iterable object; the
result of fliter is an object of filter type, and the filter object is also an iterable object;
ages = [21, 12, 35, 14, 24, 26]
x = filter(lambda age: age > 18, ages)
print(x) # <filter object at 0x0000000001DC8AC8>
print(list(x))# [21, 35, 24, 26]
for i in x:
print(i,end=' ')# 21 35 24 26
print()# 用来换下行
adults = list(x)
print(adults)# []
print(list(filter(lambda x:x%2,range(10))))# [1, 3, 5, 7, 9]
2.map class
The role of map is to make all the data in the iterable object perform the operations in the function. The result
is a map object, which can also iterate on the map object. After the iteration, the map object is empty.
ages = [12, 30, 11, 21, 14, 15]
x = map(lambda age: age * 2, ages)
print(x)# <map object at 0x00000000005B2400>
print(list(x))# [24, 60, 22, 42, 28, 30]
for i in x:
print(i)
print(list(x))# []
9. Function nesting (less used, as an understanding)
Closure: If in an internal function, a reference is made to a variable in the external scope (but not in the global scope), then the internal function is considered a closure
def outer():
m = 10
def inner():
nonlocal m # 用这个可以一修改外部局部变量
m += 1
print(m)
return inner
f = outer()
f()# 11
# 这个f就相当于是inner函数,在调用inner的时候,
# m相对于inner函数就是一个全局变量是不会被释放的
# 注意是相对的,你在外面直接打印m也是不行的
# 用处就是防止m被外部污染(以防被改变)
f()# 12
f()# 13
f()# 14
#但如果你是直接使用外部函数调用内部函数,m用完就释放了
outer()()# 11
outer()()# 11
outer()()# 11
10. Use of decorators
import time
def cal_time(fn):
print('fn={}'.format(fn))
def inner():
start=time.time()
fn()
end=time.time()
print(end - start)
return inner
@cal_time # 第一件事是调用cal_time;第二件事是把被装饰的函数传递给fn
def jjj():
x = 0
for i in range(1, 100000000):
x += i
print(x)
# 第三件事:当再次调用jjj函数时,现在的jjj函数已经不再是上面的jjj函数,而是上面的内部函数inner
# print(jjj)
jjj()
# fn=<function jjj at 0x00000261AEEC0708>
# 4999999950000000
# 5.602903842926025
def factor(fn):
def inner(x,y,*args,**kwargs):
a=kwargs.get('clock',23)
if a<23:
fn(x,y)
else:
print('太晚了睡觉吧')
return inner
@factor
def play_game(name,game):
print('{}正在玩{}'.format(name,game))
# 注意这里给play_game函数传参的时候其实是给inner函数传参
play_game('张三','王者荣耀',d=12,c=13)
play_game('张三','王者荣耀',d=12,c=13,clock=21)
Summary of built-in functions
Not complete, but master so much first
Function name | effect |
---|---|
all | Convert all elements to boolean values, only if all are True, it is True, otherwise it is False |
any | Convert all elements to boolean values, one is True is True, all is False is False |
bin | Convert numbers to binary |
oct | Convert number to octal |
hex | Convert numbers to hexadecimal |
chr | Convert character encoding to corresponding character |
words | Convert the corresponding character to character encoding |
to you | Can list all properties and methods of the object |
divmod | Find the quotient and remainder of the division of two numbers |
eval | Execute python code in string |
exit | End the program with the specified exit code |
globals | Used to view all global variables |
locals | Used to view all local variables |
help | Used to view the help documentation |
id | Get the memory address of a data |
isinstance | Determine whether an object is created by a class |
issubclass | Determine whether a class is a subclass of another class |
len | Get the length |
iter | Get iterator of iterable object |
next | The for...in loop is essentially calling the next method of the iterator |
max | Find the maximum number |
min | Find the smallest number |
open | Used to open a file |
pow | Find the nth power of a number |
round | Round to the specified decimal place |
sum | Used to sum |
note
Function cannot have the same name, a function after the same name will overwrite the previous function