欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python必備技巧之函數(shù)的使用詳解

 更新時間:2022年04月04日 09:39:02   作者:五包辣條!  
這篇文章主要為大家詳細介紹了Python中函數(shù)的基本使用教程,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

1.如何用函數(shù)

先定義后調(diào)用,定義階段只檢測語法,不執(zhí)行代碼

調(diào)用階段,開始執(zhí)行代碼

函數(shù)都有返回值

定義時無參,調(diào)用時也是無參

定義時有參,調(diào)用時也必須有參

2.默認參數(shù)陷阱

2.1針對可變數(shù)據(jù)類型,不可變不受影響

def c(a=[]):
    a.append(1)
    print(a)
c()
c()
c()

結(jié)果:

[1]
[1, 1]
[1, 1, 1]

def c(a=[]):
    a.append(1)
    print(a)
c([])
c([])
c([])

結(jié)果:

[1]
[1]
[1]

3.名稱空間和作用域

名稱空間就是用來存放名字與值內(nèi)存地址綁定關(guān)系的地方(內(nèi)存空間)

但凡查找值一定要通過名字,訪問名字必須去查找名稱空間

名稱空間分為三大類

內(nèi)置名稱空間: 存放的是python解釋器自帶的名字

生命周期: 在解釋器啟動時則生效,解釋器關(guān)閉則失效

全局名稱空間: 存放的是文件級別的名字

生命周期: 在解釋器解釋執(zhí)行python文件時則生效,文件執(zhí)行完畢后則失效

局部名稱空間: 在函數(shù)內(nèi)定義的名字

生命周期: 只在調(diào)用函數(shù)時臨時產(chǎn)生該函數(shù)的局部名稱空間,該函數(shù)調(diào)用完畢則失效

加載順序

內(nèi)置->全局->局部

查找名字的順序

基于當前所在位置往上查找

假設(shè)當前站在局部,查找順序:局部->全局->內(nèi)置

假設(shè)當前站在全局,查找順序:全局->內(nèi)置

名字的查找順序,在函數(shù)定義階段就已經(jīng)固定死了(即在檢測語法時就已經(jīng)確定了名字的查找順序),與函數(shù)的調(diào)用位置無關(guān)

也就是說無論在任何地方調(diào)用函數(shù),都必須回到當初定義函數(shù)的位置去確定名字的查找關(guān)系

作用域: 作用域指的就是作用的范圍

全局作用域: 包含的是內(nèi)置名稱空間與全局名稱空間中的名字

特點: 全局有效,全局存活

局部作用域: 包含的是局部名稱空間中的名字

特點: 局部有效,臨時存活

global: 在局部聲明一個名字是來自于全局作用域的,可以用來在局部修改全局的不可變類型

nonlocal: 聲明一個名字是來自于當前層外一層作用域的,可以用來在局部修改外層函數(shù)的不可變類型

4.閉包函數(shù)

定義在函數(shù)內(nèi)部且包含對外部函數(shù)的作用域名字的引用,需要結(jié)合函數(shù)對象的概念將閉包函數(shù)返回到全局作用域去使用,從而打破函數(shù)的層級限制

閉包函數(shù)提供了一種為函數(shù)體傳值的解決方案

def func():
    name='egon'
    def inner():
        print(name)
    return inner
inner = func()
inner()

5.函數(shù)的參數(shù)

5.1定義階段

位置形參

在定義階段從左往右的順序依次定義的形參

默認形參

在定義階段已經(jīng)為其初始化賦值

關(guān)鍵字參數(shù)

自由主題

可變長度的形參args

溢出的位置參數(shù),打包成元組,給接受,賦給args的變量名

命名關(guān)鍵字參數(shù)

放在*和之間的參數(shù),必須按照key=value形式傳值

可變長度的位置形參kwargs

溢出的關(guān)鍵字實參,打包成字典,給**接受,賦給變量kwargs

形參和實參關(guān)系: 在調(diào)用函數(shù)時,會將實參的值綁定給形參的變量名,這種綁定關(guān)系臨時生效,在調(diào)用結(jié)束后就失效了

5.2調(diào)用階段

位置實參

調(diào)用階段按照從左往右依次傳入的傳入的值,會與形參一一對應(yīng)

關(guān)鍵字實參

在調(diào)用階段,按照key=value形式指名道姓的為形參傳值

實參中帶*的,再傳值前先將打散成位置實參,再進行賦值

實參中帶的**,在傳值前先將其打散成關(guān)鍵字實參,再進行賦值

6.裝飾器:閉包函數(shù)的應(yīng)用

裝飾器就是用來為被裝飾器對象添加新功能的工具

**注意:**裝飾器本身可以是任意可調(diào)用對象,被裝飾器的對象也可以是任意可調(diào)用對象

為何使用裝飾器

**開放封閉原則:**封閉指的是對修改封閉,對擴展開放

6.1裝飾器的實現(xiàn)必須遵循兩大原則

1. 不修改被裝飾對象的源代碼`

2. 不修改被裝飾器對象的調(diào)用方式

裝飾器的目標:就是在遵循1和2原則的前提下為被裝飾對象添加上新功能

6.2裝飾器語法糖

在被裝飾對象正上方單獨一行寫@裝飾器的名字

python解釋器一旦運行到@裝飾器的名字,就會調(diào)用裝飾器,然后將被裝飾函數(shù)的內(nèi)存地址當作參數(shù)傳給裝飾器,最后將裝飾器調(diào)用的結(jié)果賦值給原函數(shù)名 foo=auth(foo) 此時的foo是閉包函數(shù)wrapper

6.3無參裝飾器

import time
def timmer(func):
    def wrapper(*args,**kwargs):
        start_time=time.time()
        res=func(*args,**kwargs)
        stop_time=time.time()
        print('run time is %s' %(stop_time-start_time))
        return res
    return wrapper

@timmer
def foo():
    time.sleep(3)
    print('from foo')
foo()

6.4有參裝飾器

def auth(driver='file'):
    def auth2(func):
        def wrapper(*args,**kwargs):
            name=input("user: ")
            pwd=input("pwd: ")

        if driver == 'file':
            if name == 'egon' and pwd == '123':
                print('login successful')
                res=func(*args,**kwargs)
                return res
        elif driver == 'ldap':
            print('ldap')
    return wrapper
return auth2

@auth(driver='file')
def foo(name):
    print(name)

foo('egon')

7.題目

#題目一:
db='db.txt'
login_status={'user':None,'status':False}
def auth(auth_type='file'):
    def auth2(func):
        def wrapper(*args,**kwargs):
            if login_status['user'] and login_status['status']:
                return func(*args,**kwargs)
            if auth_type == 'file':
                with open(db,encoding='utf-8') as f:
                    dic=eval(f.read())
                name=input('username: ').strip()
                password=input('password: ').strip()
                if name in dic and password == dic[name]:
                    login_status['user']=name
                    login_status['status']=True
                    res=func(*args,**kwargs)
                    return res
                else:
                    print('username or password error')
            elif auth_type == 'sql':
                pass
            else:
                pass
        return wrapper
    return auth2

@auth()
def index():
    print('index')

@auth(auth_type='file')
def home(name):
    print('welcome %s to home' %name)


# index()
# home('egon')

#題目二
import time,random
user={'user':None,'login_time':None,'timeout':0.000003,}

def timmer(func):
    def wrapper(*args,**kwargs):
        s1=time.time()
        res=func(*args,**kwargs)
        s2=time.time()
        print('%s' %(s2-s1))
        return res
    return wrapper


def auth(func):
    def wrapper(*args,**kwargs):
        if user['user']:
            timeout=time.time()-user['login_time']
            if timeout < user['timeout']:
                return func(*args,**kwargs)
        name=input('name>>: ').strip()
        password=input('password>>: ').strip()
        if name == 'egon' and password == '123':
            user['user']=name
            user['login_time']=time.time()
            res=func(*args,**kwargs)
            return res
    return wrapper

@auth
def index():
    time.sleep(random.randrange(3))
    print('welcome to index')

@auth
def home(name):
    time.sleep(random.randrange(3))
    print('welcome %s to home ' %name)

index()
home('egon')

#題目三:簡單版本
import requests
import os
cache_file='cache.txt'
def make_cache(func):
    def wrapper(*args,**kwargs):
        if not os.path.exists(cache_file):
            with open(cache_file,'w'):pass

        if os.path.getsize(cache_file):
            with open(cache_file,'r',encoding='utf-8') as f:
                res=f.read()
        else:
            res=func(*args,**kwargs)
            with open(cache_file,'w',encoding='utf-8') as f:
                f.write(res)
        return res
    return wrapper

@make_cache
def get(url):
    return requests.get(url).text


# res=get('https://www.python.org')

# print(res)

#題目四:擴展版本
import requests,os,hashlib
engine_settings={
    'file':{'dirname':'./db'},
    'mysql':{
        'host':'127.0.0.1',
        'port':3306,
        'user':'root',
        'password':'123'},
    'redis':{
        'host':'127.0.0.1',
        'port':6379,
        'user':'root',
        'password':'123'},
}

def make_cache(engine='file'):
    if engine not in engine_settings:
        raise TypeError('egine not valid')
    def deco(func):
        def wrapper(url):
            if engine == 'file':
                m=hashlib.md5(url.encode('utf-8'))
                cache_filename=m.hexdigest()
                cache_filepath=r'%s/%s' %(engine_settings['file']['dirname'],cache_filename)

                if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
                    return open(cache_filepath,encoding='utf-8').read()

                res=func(url)
                with open(cache_filepath,'w',encoding='utf-8') as f:
                    f.write(res)
                return res
            elif engine == 'mysql':
                pass
            elif engine == 'redis':
                pass
            else:
                pass

        return wrapper
    return deco

@make_cache(engine='file')
def get(url):
    return requests.get(url).text

# print(get('https://www.python.org'))
print(get('https://www.baidu.com'))


#題目五
route_dic={}

def make_route(name):
    def deco(func):
        route_dic[name]=func
    return deco
@make_route('select')
def func1():
    print('select')

@make_route('insert')
def func2():
    print('insert')

@make_route('update')
def func3():
    print('update')

@make_route('delete')
def func4():
    print('delete')

print(route_dic)


#題目六
import time
import os

def logger(logfile):
    def deco(func):
        if not os.path.exists(logfile):
            with open(logfile,'w'):pass

        def wrapper(*args,**kwargs):
            res=func(*args,**kwargs)
            with open(logfile,'a',encoding='utf-8') as f:
                f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__))
            return res
        return wrapper
    return deco

@logger(logfile='aaaaaaaaaaaaaaaaaaaaa.log')
def index():
    print('index')

index()

到此這篇關(guān)于Python必備技巧之函數(shù)的使用詳解的文章就介紹到這了,更多相關(guān)Python函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論