Home  >  Article  >  Backend Development  >  Summarize the advanced use of Python functions

Summarize the advanced use of Python functions

WBOY
WBOYforward
2022-06-02 11:57:552200browse

This article brings you relevant knowledge about python, which mainly introduces how to use advanced functions, including the naming and scope of functions, nesting and functions of functions Let’s take a look at the domain chain, the nature of function names, etc. I hope it will be helpful to everyone.

Summarize the advanced use of Python functions

Recommended learning: python video tutorial

1. Namespace and scope of functions

1. Function namespace

  • #What is a namespace?

If there is a string of code, observe its output:

def f():
    a = 1
    return a

print(a)

输出结果:
Traceback (most recent call last):
  File "E:/python代码/11/文件一.py", line 4, in <module>
    print(a)
NameError: name 'a' is not defined

An error has been reported! The error is "name 'a' is not defined". Variable a is not defined. . . Why? I clearly defined a=1!

Then we need to understand what to do when the Python code encounters a function when running:

First, after the python interpreter starts execution, it is allocated in the memory Whenever a variable is encountered in a space, the corresponding relationship between the variable name and value is recorded. But when encountering a function definition, the interpreter only symbolically reads the function name into the memory, indicating that it knows the existence of this function. As for the variables and logic inside the function, the interpreter does not care at all. When the function call is executed, the python interpreter will allocate another memory to store the content of the function. At this time, it will pay attention to the variables in the function, and the variables in the function will be stored in the newly opened memory. The variables in the function can only be used inside the function, and as the function completes execution, all contents in this memory will be cleared.

We gave this space that "stores the relationship between names and values" a name - called the namespace

The code created at the beginning to store the "variable name" "Relationship with value" space is called global namespace, and the temporary space opened during the internal operation of the function is called local namespace

  • Three major categories of function namespaces

Function namespaces are divided into three major categories

1、内置命名空间 —— python解释器
    # 就是python解释器一启动就可以使用的名字存储在内置命名空间中
    # 内置的名字在启动解释器的时候被加载进内存里
2、全局命名空间 —— 我们写的代码但不是函数中的代码
    # 是在程序从上到下被执行的过程中依次加载进内存的
    # 放置了我们设置的所有变量名和函数名
3、局部命名空间 —— 函数
    # 就是函数内部定义的名字
    # 当调用函数的时候 才会产生这个名称空间 随着函数执行的结束 这个命名空间就又消失了

#在局部:可以使用全局、内置命名空间中的名字
#在全局:可以使用内置命名空间中的名字,但是不能用局部中使用
#在内置:不能使用局部和全局的名字的

Built-in namespace: The built-in namespace stores the names (functions) provided by the Python interpreter for us. We do not need to define them. They are all familiar ones that we can use directly when opening the interpreter, such as: input, print, str, set...

  • Loading and value order among the three namespaces

Loading order: built-in namespace ( Load before the program is running > Global namespace (when the program is running: loaded from top to bottom) > Local namespace (when the program is running: loaded when called)

When called locally: local namespace> ; Global namespace> Built-in namespace

When called globally: Global namespace> Built-in namespace

Example:

a = 10
def f():
    a = 1
    print(a)
f()
print(a)

输出结果:
1
10

2 , The scope of the function

Scope is the scope, which can be divided into global scope and local scope according to the effective scope.

Global scope: includingBuilt-in namespace, global namespace, can be referenced anywhere in the entire file, and is globally valid

Local scope: local namespace, can only be within the local scopeEffective

  • globals and locals methods

locals(): The function will return all local variables at the current location in dictionary type.
globals(): The function will return all global variables at the current location in dictionary type.

def func():
    a = 1
    print(locals())
    print(globals())
    print('========================分割线==========================')
func()
print(locals())
print(globals())

Output result:

  • global关键字

1、global是Python中的全局变量关键字。
2、变量分为局部变量与全局变量,局部变量又可称之为内部变量。
3、由某对象或某个函数所创建的变量通常都是局部变量,只能被内部引用,而无法被其它对象或函数引用。
4、全局变量既可以是某对象函数创建,也可以是在本程序任何地方创建。全局变量是可以被本程序所有对象或函数引用。
5、global关键字的作用是可以使得一个局部变量为全局变量

例子:

在my函数中,在 x 前面加 global,my函数将 x 赋为8,此时全局变量中的 x 值改变。需要注意的是 global 需要在函数内部声明,若在函数外声明,则函数依然无法操作 x 。

x = 4
 
def my():
    global x
    x = 8
    print("x = ", x)
 
print("x = ", x)
my()
print("x = ", x)
 
 
输出结果是:
x = 4
x = 8
x = 8

二、函数的嵌套和作用域链

  • 函数的嵌套调用

def max2(x,y):
    m  = x if x>y else y
    return m

def max4(a,b,c,d):
    res1 = max2(a,b)
    res2 = max2(res1,c)
    res3 = max2(res2,d)
    return res3

ret = max4(1,2,4,3)
print(ret)

输出结果:
4
  • 函数的嵌套定义

def f1():
    print("in f1")
    def f2():
        print("in f2")

    f2()
f1()

输出结果:
in f1
in f2

def f1():
    def f2():
        def f3():
            print("in f3")

        print("in f2")
        f3()

    print("in f1")
    f2()


f1()

输出结果:
in f1
in f2
in f3
  • 函数的作用域链

a = 1
def outer():
    a = 5
    def inner():
        a = 2
        def inner2():
            nonlocal a
            a += 1
            print('inner2',a)
        inner2()
        print('##a##:',a)
    inner()
    print('**a**:',a)

outer()

print('全局:',a)

输出结果:
inner2 3
##a##: 3
**a**: 5
全局: 1
  • nonlocal关键字

#nonlocal 只能用于局部变量,找上层中离当前函数最近一层的局部变量且外部必须有这个变量
#声明了nonlocal的内部函数的变量修改会影响到离当前函数最近一层的局部变量
#对全局无效,在内部函数声明nonlocal变量之前不能再出现同名变量
#对局部也只是对最近一层有影响
def f1():
    a = 1
    def f2():
        nonlocal a
        a = 2
    f2()
    print('a in f1 : ',a)

f1()

输出结果:
a in f1 :  2
  • global关键字

# 对于不可变数据类型 在局部可是查看全局作用域中的变量
# 但是不能直接修改
# 如果想要修改,需要在程序的一开始添加global声明
# 如果在一个局部(函数)内声明了一个global变量,那么这个变量在局部的所有操作将对全局的变量有效

三、函数名的本质

  1. 函数名就是内存地址

  2. 函数名可以被赋值

  3. 函数名可以作为容器类型的元素

  4. 函数名可以作为函数的返回值

  5. 函数名可以作为函数的参数

def func():
    print(123)
func()
print(func)
# 函数名就是内存地址
# 函数名可以被赋值
func2 = func
func2()

#函数名可以作为容器类型的元素
l = [func,func2]
for i in l:
    i()
def func():
    print(123)

def wahaha(f):
    f()
    return f            #函数名可以作为函数的返回值
qqxing = wahaha(func)   #函数名可以作为函数的参数
qqxing()

输出结果:
123
<function func at 0x000001ADF9946280>
123
123
123
123
123
  • 思考 

如果我自己定义了一个input函数(作用:调用该函数就打印'在下周周ovo'),会不会与内置的input函数有冲突呢?

def input(a):
    print('在下周周ovo')

那么接下来的代码怎么运行呢?

def input(a):
    print('在下周周ovo')

def func():
    input('请输入')
    print(input)

func()

答案:


四、闭包

  • 闭包函数的概念

内部函数包含对外部作用域而非全剧作用域名字的引用,该内部函数称为闭包函数
#函数内部定义的函数称为内部函数

由于有了作用域的关系,我们就不能拿到函数内部的变量和函数了。如果我们就是想拿怎么办呢?返回呀!

如果函数内的变量我们要想在函数外部用,可以直接返回这个变量,那么如果我们想在函数外部调用函数内部的函数呢?那就直接将函数名字作为返回值就好

def outer():
    a = 1
    def inner():
        print(a)    #内部函数调用了外部变量a
    return inner

inn = outer()
inn()

输出结果:
1
  • 闭包函数的判断方法

判断闭包函数的方法__closure__

当运行后,如果有cell的话,就表示是闭包函数。如果没有就不是。

#输出的__closure__有cell元素 :是闭包函数
def func():
    name = 'eva'
    def inner():
        print(name)
    print(inner.__closure__)
    return inner

f = func()
f()

#输出的__closure__为None :不是闭包函数
name = 'egon'
def func2():
    def inner():
        print(name)
    print(inner.__closure__)
    return inner

f2 = func2()
f2()

输出结果:
(<cell at 0x000001E935CB0FA0: str object at 0x000001E935CC2CB0>,)
eva
None
egon
  • 闭包嵌套

顾名思义是两个或以上的闭包函数嵌套在一起

def wrapper():
    money = 10
    def func():
        name = 'zhou'    
        def inner():
            print(name,money)    #引用了func()函数中name变量引用了wrapper()函数中money变量
        return inner
    return func

f = wrapper()
i = f()
i()

输出结果:
zhuo 10

小结

#func(一个函数名)  --->>对应函数的内存地址
#函数名()---函数调用
#函数的内存地址----()函数的调用
# 作用域两种
# 全局作用域 —— 作用在全局 —— 内置和全局名字空间中的名字都属于全局作用域  ——globals()
# 局部作用域 —— 作用在局部 —— 函数(局部名字空间中的名字属于局部作用域) ——#locals()globals() : 永远打印全局的名字
#locals()  : 输出什么 根据locals所在位置
#在代码中要尽量少定义全局变量,多使用返回值和接收返回值
#函数的嵌套:
        嵌套调用
        嵌套定义:定义在内部的函数无法直接在全局被调用
#函数名的本质:
        就是一个变量,保存了函数所在的内存地址
#闭包:
        内部函数包含对外部作用域而非全剧作用域名字的引用,该内部函数称为闭包函数

推荐学习:python视频教程

The above is the detailed content of Summarize the advanced use of Python functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete