python study notes 8.2 (54-punch in on time-QQ)

Task6 functions and Lambda expressions
1. Function
Python treats functions as objects, and can be returned from another function to construct higher-order functions, such as: the parameter is a function or the return value is
the definition of the function: the function is defined with the def keyword At the beginning, followed by the function name and parentheses (). The code executed by the function starts with a colon and is indented. return [expression] End the function, optionally returning a value to the caller. Return without expression is equivalent to returning None.

def functionname(parameters):
    "函数_文档字符串"
    function_suite
    return [expression]

Function call:

def printme(str):
    print(str)


printme("我要调用用户自定义函数!")  # 我要调用用户自定义函数!
printme("再次调用同一函数")  # 再次调用同一函数
temp = printme('hello') # hello
print(temp)  # None

Function documentation:

def MyFirstFunction(name):
    "函数定义过程中name是形参"
    # 因为Ta只是一个形式,表示占据一个参数位置
    print('传递进来的{0}叫做实参,因为Ta是具体的参数值!'.format(name))


MyFirstFunction('老马的程序人生')  
# 传递进来的老马的程序人生叫做实参,因为Ta是具体的参数值!

print(MyFirstFunction.__doc__)  
# 函数定义过程中name是形参

help(MyFirstFunction)
# Help on function MyFirstFunction in module __main__:
# MyFirstFunction(name)
#    函数定义过程中name是形参

Function parameters:
Python functions have very flexible and diverse parameter forms, which can realize simple calls and pass in very complex parameters. The parameter forms from simple to complex are as follows: positional argument (positional argument)
default argument (default argument)
variable argument
(keyword argument)
named keyword argument (name keyword argument)
parameter combination

1. Location parameters

def functionname(arg1):
    "函数_文档字符串"
    function_suite
    return [expression]

arg1-positional parameters, these parameters must be fixed in position when calling a function (call function).

2. Default parameters

def functionname(arg1, arg2=v):
    "函数_文档字符串"
    function_suite
    return [expression]

arg2 = v-Default parameter = default value. When calling the function, if the value of the default parameter is not passed in, it is considered as the default value.
The default parameter must be placed after the positional parameter, otherwise the program will report an error.
Python allows the order of parameters in function call to be inconsistent with that in declaration, because the Python interpreter can match parameter values ​​with parameter names.

def printinfo(name, age=8):
    print('Name:{0},Age:{1}'.format(name, age))


printinfo('小马')  # Name:小马,Age:8
printinfo('小马', 10)  # Name:小马,Age:10

def printinfo(name, age):
    print('Name:{0},Age:{1}'.format(name, age))


printinfo(age=8, name='小马')  # Name:小马,Age:8

3. Variable parameters
As the name implies, variable parameters means that the number of parameters passed in is variable, which can be 0, 1, 2 to any number, and is a parameter of variable length.

def functionname(arg1, arg2=v, *args):
    "函数_文档字符串"
    function_suite
    return [expression]

args-Variable parameters, which can be from zero to any number, automatically assembled into tuples. Variable names with an asterisk ( ) will store all unnamed variable parameters. Such as:

def printinfo(arg1, *args):
    print(arg1)
    for var in args:
        print(var)


printinfo(10)  # 10
printinfo(70, 60, 50)

# 70
# 60
# 50

4. Keyword parameters

def functionname(arg1, arg2=v, *args, **kw):
    "函数_文档字符串"
    function_suite
    return [expression]

**kw-keyword parameters, which can be from zero to any number, automatically assembled into a dictionary. Such as:

def printinfo(arg1, *args, **kwargs):
    print(arg1)
    print(args)
    print(kwargs)


printinfo(70, 60, 50)
# 70
# (60, 50)
# {}
printinfo(70, 60, 50, a=1, b=2)
# 70
# (60, 50)
# {'a': 1, 'b': 2}

The similarities and differences between "variable parameters" and "keyword parameters" are summarized as follows:
Variable parameters allow zero to any number of parameters to be passed in, and they are automatically assembled into a tuple when the function is called. Keyword parameters allow zero to any number of parameters to be passed in, and they are automatically assembled into a dictionary (dict) inside the function.

  1. Named keyword parameters
def functionname(arg1, arg2=v, *args, *, nkw, **kw):
    "函数_文档字符串"
    function_suite
    return [expression]

*, nkw-named keyword parameter, the keyword parameter that the user wants to enter, the definition method is to add a separator * in front of nkw. If you want to limit the names of keyword parameters, you can use "Named Keyword Parameters". When using named keyword parameters, pay special attention to the lack of parameter names. Such as:

def printinfo(arg1, *, nkw, **kwargs):
    print(arg1)
    print(nkw)
    print(kwargs)


printinfo(70, nkw=10, a=1, b=2)
# 70
# 10
# {'a': 1, 'b': 2}

printinfo(70, 10, a=1, b=2)
# TypeError: printinfo() takes 1 positional argument but 2 were given

The parameter name nwk is not written, so 10 is regarded as a "positional parameter", and the original function has only one positional function, and now two are called, so the program will report an error.

6. Parameter combination
defines a function in Python. You can use positional parameters, default parameters, variable parameters, named keyword parameters, and keyword parameters. 4 of these 5 parameters can be used together, but note that the parameter definition The order must be: positional parameters, default parameters, variable parameters and keyword parameters. Positional parameters, default parameters, named keyword parameters, and keyword parameters. Pay attention to the syntax of defining variable parameters and keyword parameters:
*args is a variable parameter, args receives a tuple
**kw is a keyword parameter, kw receives a dict
named keyword parameter to limit the caller can The name of the incoming parameter can also provide a default value. Don't forget to write the delimiter * when defining named keyword parameters, otherwise positional parameters are defined.
Warning: Although you can combine up to 5 parameters, do not use too many combinations at the same time, otherwise the function is difficult to understand.

The return value of the function
such as:

def add(a, b):
    return a + b


print(add(1, 2))  # 3
print(add([1, 2, 3], [4, 5, 6]))  # [1, 2, 3, 4, 5, 6]

def back():
    return [1, '小马的程序人生', 3.14]


print(back())  # [1, '小马的程序人生', 3.14]

Variable scope

In Python, the variables of the program are not accessible at any location, and the access permissions depend on where the variable is assigned. The variable defined inside the function has a local scope, which is called a local variable. Variables defined outside the function have a global scope, which is called a global variable. Local variables can only be accessed within the function in which they are declared, while global variables can be accessed within the scope of the entire program.
When the inner scope wants to modify the variables of the outer scope, the global and nonlocal keywords must be used. Such as:

num = 1


def fun1():
    global num  # 需要使用 global 关键字声明
    print(num)  # 1
    num = 123
    print(num)  # 123


fun1()
print(num)  # 123

Built-in functions
such as:

def outer():
    print('outer函数在这被调用')

    def inner():
        print('inner函数在这被调用')

    inner()  # 该函数只能在outer函数内部被调用


outer()
# outer函数在这被调用
# inner函数在这被调用

Closures
Closures are an important grammatical structure of functional programming and are a special kind of built-in function. If a reference is made to an outer non-globally scoped variable in an internal function, then the internal function is considered a closure. Through closures, variables in the outer non-global scope can be accessed, and this scope is called the closure scope.

def funX(x):
    def funY(y):
        return x * y

    return funY


i = funX(8)
print(type(i))  # <class 'function'>
print(i(5))  # 40

The return value of a closure is usually a function. Such as:

def make_counter(init):
    counter = [init]

    def inc(): counter[0] += 1

    def dec(): counter[0] -= 1

    def get(): return counter[0]

    def reset(): counter[0] = init

    return inc, dec, get, reset


inc, dec, get, reset = make_counter(0)
inc()
inc()
inc()
print(get())  # 3
dec()
print(get())  # 2
reset()
print(get())  # 0

If you want to modify the variable in the scope of the closure, you need the nonlocal keyword, such as:

def outer():
    num = 10

    def inner():
        nonlocal num  # nonlocal关键字声明
        num = 100
        print(num)

    inner()
    print(num)


outer()

# 100
# 100

Recursion
If a function calls itself internally, the function is recursive.
For example: n! = 1 x 2 x 3 x… xn is implemented as follows:

# 利用循环
n = 5
for k in range(1, 5):
    n = n * k
print(n)  # 120

# 利用递归
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)


print(factorial(5)) # 120

The Fibonacci sequence f(n)=f(n-1)+f(n-2), f(0)=0 f(1)=1 is implemented as follows:

# 利用循环
i = 0
j = 1
lst = list([i, j])
for k in range(2, 11):
    k = i + j
    lst.append(k)
    i = j
    j = k
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

# 利用递归
def recur_fibo(n):
    if n <= 1:
        return n
    return recur_fibo(n - 1) + recur_fibo(n - 2)


lst = list()
for k in range(11):
    lst.append(recur_fibo(k))
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Set the number of recursion levels, Python default recursion level is 100, such as:

import sys

sys.setrecursionlimit(1000)

2. Lambda expression
Anonymous function definition There are two types of functions in Python: the first type: the normal function defined with the def keyword; the second type: the anonymous function defined with the lambda keyword python uses the lambda keyword to create anonymity Function, instead of the def keyword, it has no function name, and its grammatical structure is as follows:
lambda argument_list: expression

lambda-keywords to define anonymous functions.
argument_list-function parameters, they can be positional parameters, default parameters, keyword parameters, and the same type of parameters in the normal function.
:- Colon, add a colon between function parameters and expressions.
expression-just an expression, input function parameters, output some values.

Note: There is no return statement in expression, because lambda does not need it to return, and the result of the expression itself is the return value. An anonymous function has its own namespace and cannot access parameters outside of its parameter list or in the global namespace.

def sqr(x):
    return x ** 2


print(sqr)
# <function sqr at 0x000000BABD3A4400>

y = [sqr(x) for x in range(10)]
print(y)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

lbd_sqr = lambda x: x ** 2
print(lbd_sqr)
# <function <lambda> at 0x000000BABB6AC1E0>

y = [lbd_sqr(x) for x in range(10)]
print(y)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


sumary = lambda arg1, arg2: arg1 + arg2
print(sumary(10, 20))  # 30

func = lambda *args: sum(args)
print(func(1, 2, 3, 4, 5))  # 15

Application of anonymous functions Functional programming means that every piece of code is immutable and consists of pure functions. The pure function here means that the functions are independent of each other and do not affect each other. For the same input, there will always be the same output without any side effects.
Non-functional programming:

def f(x):
    for i in range(0, len(x)):
        x[i] += 10
    return x


x = [1, 2, 3]
f(x)
print(x)
# [11, 12, 13]

Functional programming

def f(x):
    y = []
    for item in x:
        y.append(item + 10)
    return y


x = [1, 2, 3]
f(x)
print(x)
# [1, 2, 3]

Anonymous functions are often used in high-order functions in functional programming. There are two main forms: parameters are functions (filter, map) and return values ​​are functions (closure). For example, in filter and map functions Application: filter(function, iterable) Filter sequence, filter out elements that do not meet the conditions, and return an iterator object. If you want to convert to a list, you can use list() to convert.

odd = lambda x: x % 2 == 1
templist = filter(odd, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(templist))  # [1, 3, 5, 7, 9]

map(function, *iterables) Map the specified sequence according to the provided function.

In addition to Python built-in functions, we can also define higher-order functions ourselves.

def apply_to_list(fun, some_list):
    return fun(some_list)

lst = [1, 2, 3, 4, 5]
print(apply_to_list(sum, lst))
# 15

print(apply_to_list(len, lst))
# 5

print(apply_to_list(lambda x: sum(x) / len(x), lst))
# 3.0

Practice questions:
Functions and Lambda expressions

  1. How to document a function?
    Answer:
    After def statement ⾯ documentation that the comment in quotes (single quote, double quote, the three can be cited) ⾥ ⾯ on ⾏, the documentation that can function. DOC visit.
  2. How to annotate function parameters and return values?
    Answer: When the
    code is executed, the annotations will not be processed, but stored in the annotations attribute (a dictionary) of the function.
    def function(text: str, max_len:'int> 0'= 80) -> str:
    Each parameter in the function declaration can be added with a comment expression after:. If the parameter has a default value, the note is between the parameter name and the = sign. If you want to
    annotate the return value, add -> and an expression between) and the: at the end of the function declaration.
    The only thing Python does with annotations is to store them in the annotations attribute of the function. That's it, Python does not
    check, enforce, verify, and do nothing. In other words, the annotation has no meaning to the Python interpreter. Annotations are just metadata
    , which can be used by tools such as IDEs, frameworks, and decorators.
  3. How to update immutable elements such as numbers, strings, and tuples in closures.
    Answer: We know that in a closure, the declared variable is a local variable, and an error will be reported if the local variable changes.
    To solve this problem, Python 3 introduces the nonlocal declaration. Its purpose is to mark variables as free variables.
    4. Sort the two-dimensional list a = [[6, 5], [3, 7], [2, 8]] according to the size of the first and last elements of each row. (Using lambda expressions)
sorted(a, key=lambda x:x[0]) # 根据每一行的首元素排序,默认reverse=False
sorted(a, key=lambda x:x[-1]) # 根据每一行的尾元素排序,设置reverse=True实现逆序

Guess you like

Origin blog.csdn.net/m0_45672993/article/details/107752971