Python3 的內置函數和閉包


1、global 關鍵字

  如果在函數內部需要修改全局變量那么需要使用global關鍵字

x=1
def mfun():
    global x
    x=2
    print(x)
>>> mfun()
2

2、內嵌函數(內部函數)

  內部函數的的作用域在外部函數作用於之內,及只能在外部函數內調用內部函數

def outside():
    print("正在調用outside")
    def inside():   
        print("正在調用inside")
    inside()
outside()
inside()#這句話是錯的

正在調用outside
正在調用inside
Traceback (most recent call last):
  File "C:\Users\ENVY\Desktop\learnning Python\text.py", line 7, in <module>
    inside()
NameError: name 'inside' is not defined

3、閉包(closure)

def line_conf():
    def line(x):
        return 2*x+1
    return line       # return a function object

my_line = line_conf()
print(my_line(5))
def line_conf():
    b = 15
    def line(x):
        return 2*x+b
    return line       # return a function object
 
b = 5
my_line = line_conf()
print(my_line(5))    # 返回25

在內部函數中只能對外部函數的局部變量進行訪問,但是不能修改,如果需要修改則需要用到nonlocal關鍵字,委屈求全可以使用“容器類型”代替

def line_conf():
    b = 15
    def line(x):
        nonlocal b
        b=20
        return 2*x+b
    return line       # return a function object
 
b = 5
my_line = line_conf()
print(my_line(5))     #返回30
def line_conf():
    b = [15]
    def line(x):
        b[0]=20
        return 2*x+b[0]
    return line       # return a function object
 

my_line = line_conf()
print(my_line(5)) #返回30

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM