12日目の閉鎖機能/デコレータ

閉鎖機能

閉鎖機能:関数や変数ラップ

def make_averager():
    series = []

    def averager(new_value):
        series.append(new_value)
        total = sum(series)
        return total/len(series)
    return averager

avg = make_averager()
print(avg(10))
print(avg(20))
print(avg(30))

10.0
15.0
30.0

デコレーター

デコレータは関数であります

2つの原則:

  1. 機能のソースコードを変更せずに飾られます
  2. コールが装飾されている機能を変更しないでください
def deco(func):
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        print("I'm Tiny")
        return res

    return wrapper


@deco
def say(x):
    print(f'Hello,{x}')
    return 'Nice to meet you'


say = say('nick')
print(say)

実際には、ラッパーを()呼び出しているとき、デコレータの上、最後の呼び出しは()を言ってもRESの上に、つまり、この値を返す必要が内側に)(例えば)は値、そしてラッパーを(返す場合

あなたが)(と言うのパラメータを渡す必要がある場合には、ラッパーは()同じパラメータの範囲内で渡されるべきですが、私たちは)(パラメータが渡されたと言うことかわからないので、全ての*引数を使用することができ、**ユニバーサルパラメータを表すためにkwargsから

Pythonのデコレータのシンタックスシュガー

装飾的な機能ですぐ上、および別の行に書かれています@装饰器名

あなたは装飾する関数を直接呼び出すことができます

三のデコレータ

import time

current_uesr = {'username': None}


def auth(engine='file'):

    def login(func):
        # func = 最原始的index
        def wrapper(*args, **kwargs):

            if current_user['username']:
                res = func(*args, **kwargs)

                return res

            user = input('username: ').strip()
            pwd = input('password: ').strip()

            if engine == 'file':
                print('base of file')
                if user == 'nick' and pwd == '123':
                    print('login successful')
                    current_uesr['usre'] = user
                    res = func(*args, **kwargs)

                    return res
                else:
                    print('user or password error')
            elif engine == 'mysql':
                print('base of mysql, please base of file')
            elif engine == 'mongodb':
                print('base of mongodb, please base of file')
            else:
                print('please base of file')

        return wrapper

    return login


@auth(engine='mysql')
def home(name):
    print(f"welcome {name} to home page")
    time.sleep(1)


@auth(engine='file')
def index():
    print('welcome to index')
    time.sleep(1)


res = index()

ユーザ名:ニックの
パスワード:123
ファイルのベース
ログインに成功し
たインデックスへようこそ

おすすめ

転載: www.cnblogs.com/2222bai/p/11574680.html