0925課堂小結 函數小結


函數的定義

def 函數名():
    pass

函數的三種定義方式

空函數

def func():
    pass

有參函數

def func(args):
    pass

無參函數

def func():
    pass

函數的調用

函數名()

函數的返回值

  1. return 可以返回值
  2. return 可以終止函數
  3. return 可以返回多個值,用元組返回

函數的參數

形參

位置形參

從左到右依次接收位置實參

默認形參

具有默認值;它必須放在位置形參后面

實參

位置實參

從左到右依次傳值給位置形參

關鍵字實參

按照形參名傳值;它必須放在位置實參后面

可變長參數

*

*形參:接收多余的位置實參,用元組接收

*實參:打散可迭代對象,當作位置實參傳給形參

**

**形參:接收多余的關鍵字實參,用字典接收

**實參:打散字典,當作關鍵字實參傳給形參

def func(*args,**kwargs): # 接收所有多余的參數
    pass

函數對象

def func():
    pass

引用

f1 = func

容器類元素

lt = [func]

函數的返回值

def f2():
    return func

f3 = f2()

函數的參數

def f2(func):
    pass

f2(func)

函數嵌套

def f1():
    def f2():
        pass

名稱空間與作用域

內置名稱空間

內置函數

全局名稱空間

除了內置和局部都是全局

局部名稱空間

函數內部的

執行順序

內置 --》 全局 --》 局部

搜索順序

從當前開始 局部 -》 全局 -》 內置

全局作用域

全局的x和局部的x沒有半毛錢關系

x = 1

def f1():
    x = 3

f1()
print(x)

局部作用域

局部1x和局部2的x沒有半毛錢關系

def f1():
    x = 1
    def f2():
        x = 3
        
def f3():
    x = 4

global

x = 1

def f1():
    global x  # 讓下面的x變成全局的x
    x = 3

f1()
print(x)

nonlocal

def f1():
    x = 1
    def f2():
        nonlocal x
        x = 3
        
def f3():
    x = 4

可變數據類型會打破作用域關系

閉包函數

def a(x):
    
    def b():
        print(x)
    return b

c = a(100)
x = 20
c()

裝飾器

  1. 本質就是函數
  2. 不修改源代碼
  3. 不改變調用方式

二層裝飾器

import time

def index(x):
    
	return 123

def time_count(func):

    def wrapper(*args,**kwargs):
        start = time.time()
        res = func(*args,**kwargs)
        end = time.time()
        print(end - start)
        
        return res
       
    return wrapper
    
index = time_count(index)
res = index(10)  # wrapper()

兩層裝飾器模板

def deco(func):
    def wrapper(*args,**kwargs):
        res = func(*args,**kwargs)
        return res
    return wrapper

@deco
def index():
    pass

三層裝飾器

def sanceng(x):
    def deco(func):
        def wrapper(*args,**kwargs):
            res = func(*args,**kwargs)
            return res
        return wrapper
    return deco

@sanceng(10)
def index():
    pass

迭代器

可迭代對象

含有iter方法 --》除了數字

迭代器對象

含有iter和next方法的 --》 文件

三元表達式

列表推導式

字典生成式

生成器表達式

g = (i for i in range(10))

print(next(g)) # g.__next__()

生成器

含有yield的函數

yield

  1. 暫停函數
  2. 一個next可以拿到一個yield的值

遞歸

函數調用函數本身;有退出條件

count = 0
def a():
    global count
    print(count)
    count += 1
    if count == 100:
        return 
    a()

遞歸能干的事情,絕大多數能用循環代替

匿名函數

lambda 參數:返回值

與max/min/filter/map/sorted/sum

內置函數

enumerate 獲取索引+值

面向過程編程

類似與流水線


免責聲明!

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



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