Python basic knowledge combing-function

Python basic knowledge combing-function

Function basis

Let's look at a simple example first

def sum_numbers(a,b):
  return a+b
result = sum_numbers(3,5)
print(result)
# 输出
8

When calling a function, the function must be declared before the function call, otherwise an error may be reported.

result = sum_numbers(3,5)
def sum_numbers(a=0,b=0):
  return a+b
print(result)
# 输出
NameError:name 'sum_numbers' is not defined

Generally speaking, we will set a default value and use the default value when it is not changed. In most cases, some values ​​generally do not need to be changed.

def sum_numbers(a=0,b=0):
  return a+b
result = sum_numbers(3,5)
print(result)
# 输出
8

One feature of Python compared to other languages ​​is that Python is a dynamically typed language that can accept any type of data (integer, floating point, string, etc.). This also applies to parameters. The sum_numbers function we just defined You can also pass a list as a parameter, which means to connect two lists:

def sum_numbers(a,b):
  return a+b
result = sum_numbers([1,3,5,7],[2,4,6,8])
print(result)
# 输出
[1, 3, 5, 7, 2, 4, 6, 8]

Similarly, strings can also be spliced

def sum_numbers(a,b):
  return a+b
result = sum_numbers('welcome to ','https://reid.run')
print(result)
# 输出
welcome to https://reid.run

In Python, we don't need to consider the type of input data. We call this feature of Python polymorphism , but it will bring many problems in actual use. Therefore, it is necessary to add data type checking at the beginning.

Another major feature of Python is that Python supports nesting of functions. Let's look at an example:

def f1():
  print('hello')
  def f2():
      print('reid.run')
  f2()

f1()
# 输出
hello
reid.run

Nesting of functions:

  1. The nesting of functions can protect the privacy inside the function. The internal function can only be accessed by the external function and will not be exposed to the global scope. When accessing the database through pymysql, you definitely do not want (database user and password) to be exposed, then You can use the nesting of functions to encapsulate them in internal functions and access them only through internal functions.
  2. Reasonable function nesting can improve the efficiency of the program. (For example: Tower of Hanoi, recursively calculate the factorial of a number)

Scope of function variables

If the variable is defined inside the function, it is called a local variable and is only valid inside the function. When the function is executed, the local variable will be recovered and cannot be accessed.

If the variable is defined at the entire file level, then this variable is called a global variable. Global variables can be accessed inside and outside the function, but the value of global variables cannot be changed inside the function .

MAX_NUMBER = 1
def change_number(value):
    # 省略
    MAX_NUMBER +=1
    # 省略
change_number(2)
UnboundLocalError: local variable 'MAX_NUMBER' referenced before assignment

In Python, the Python interpretation power defaults to the variables inside the function as local variables, but it is found that the local variable MAX_NUMBER is not declared, so it cannot be called, so if we must change the value of the global variable inside the function, we must use the global declaration :

MAX_NUMBER = 1
def change_number(value):
    # 省略
    global MAX_NUMBER 
    MAX_NUMBER += 1
    # 省略
change_number(2)

The global keyword here is used to declare that the MAX_NUMBER variable inside the function is the previously defined global variable. It is neither a new global variable nor a local variable inside the function. In this way, the function can modify the global variable inside the function value.

When a variable with the same name is defined both inside and outside the function, the Python interpreter will first read the value of the internal variable:

MAX_NUMBER = 1 # 外部变量
def change_number():
    MAX_NUMBER = 5 # 内部变量
    return MAX_NUMBER

print(change_number())
# 输出
5

Similarly, for nested functions, the inner function can access the variables defined by the outer function, but it cannot be modified. If you want to modify it, you must add the nonlocal keyword:

def outer():
    x = 'local'
    def inner():
        nonlocal x # nonlocal关键词表示这里的x就是外部函数outer定义的变量x
        x = 'nonlocal'
        print('inner:',x)
    inner()
    print('outer:',x)
outer()
# 输出
inner: nonlocal
outer: nonlocal
# nonlocal关键词改变了外部变量 x 的值

If the nonlocal keyword is not added, and the variable of the internal function and the variable of the external function have the same name, the internal function variable will override the external function variable.

def outer():
    x = 'local'
    def inner():
        x = 'nonlocal'
        print('inner:',x)
    inner()
    print('outer:',x)
outer()
# 输出
inner: nonlocal
outer: local
# 没有nonlocal关键词,内部函数的变量覆盖了外部函数的变量

Closure

In one sentence, a closure is composed of two nested functions. The return value of the outer function will be a reference to the inner function, which is mainly used for decorators.

The following pseudo code is used to describe the format of the closure:

def 外函数(参数):
  def 内函数(参数):
    print('内函数执行',参数)
  return 内函数
内函数的引用 = 外函数('传入参数')
内层函数的引用()

Let's look at a simple example:

def func(a,b):
    def line(x):
        return a * x - b
    return line

line = func(2,3)
result = line(4)
print(result)
# 输出
2 * 4 - 3 = 5






For the follow-up update of the blog post, please follow my personal blog: Stardust Blog

Guess you like

Origin blog.csdn.net/u011130655/article/details/113018840