python中的装饰器

一、装饰器

         装饰器本质是一个Python函数,它可以让其他函数在不需要作任何

代码变动的前提下增加额外的功能,装饰器的返回值也是一个函数对象,

它经常用于有切面需求的场景,比如插入日志、性能测试、事物处理、缓

存、权限校验等场景,装饰器是解决这类问题的绝佳设计,有了装饰器,

我们就可以抽离出大量于函数的功能本身无关的雷同代码并继续使用。

 
装饰器:
把一个函数当作参数传递给另一个函数,返回一个替代版的函数
本质上就是一个返回函数的函数‘

在不改变原函数的基础上 给函数增加功能

函数装饰的格式


1、函数装饰器的格式

(1)装饰的原函数

(2)@(装饰器的函数名)

(3)原函数(装饰的对象)

如:def outter(f):                    ##函数的装饰器
    def inner():                    ##函数装饰器中要装饰的格式
        print('*********')
        f()                        ##f表示调用原函数
            print('!!!!!!!!!')
    return inner                    ##(返回的是函数而不是结果)修饰的结果返回到原函数的结果赋在将赋值的结果传到装饰壳进行下一步的调用
@outer                            ##原函数的内容
def fun():                        
    print('hello')
fun()


 

"""
装饰器:
把一个函数当作参数传递给另一个函数,返回一个替代版的函数
本质上就是一个返回函数的函数

在不改变原函数的基础上 给函数增加功能
"""
def fun():
    # print('**********')
    print('hello')

print('*******')
fun()
#
# def outer(f):
def inner(f):
    print('***********')
    f()
    print('!!!!!!!!!')
    return inner
@inner
def fun():
    # print('**********')
    print('hello')
# fun = outer(fun)
fun()

@outer #语法糖
def func():
    print('lalalala')
func()
def outer(f):
    def inner(age):
        if age <=0:
            age = 0
        f(age)
    return inner

@outer
def say(age):
    print('%d years old' %(age))

say(-10)

 

 

 

2、

"""
装饰器实现一个函数计时器
1.被装饰的函数如果有 返回值的时候 怎么办?
2.如何保留被装饰函数的函数名字和帮助文档信息?

 

"""
装饰器实现一个函数计时器
1.被装饰的函数如果有 返回值的时候 怎么办?
2.如何保留被装饰函数的函数名字和帮助文档信息?

"""
import functools
import random
import string
import time
li = [random.choice(string.ascii_letters) for i in range(100)]
print(time.time())
def timeit(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kwargs): #接收可变参数 和 关键字参数
        """这是一个装饰器timeit"""
        # 在函数执行之前
        start_time = time.time()
        # 执行函数
        res = fun(*args,**kwargs)
        # 在函数执行之后
        end_time = time.time()
        print('运行时间为:%.6f' %(end_time - start_time))
        return res
    return wrapper

@timeit
def con_add():
    s = ''
    for i in li:
        s += (i+'')
    print(s)
@timeit
def join_add():
    print(','.join(li))

# con_add()
# join_add()

@timeit
def fun_list(n):
    """这是一个fun_list函数"""
    return [2 * i for i in range(n)]
@timeit
def fun_map(n):
    return list(map(lambda x:x*2,range(n)))


# fun_list(1000000)
# fun_map(1000000)

print(fun_list.__name__)
print(fun_list.__doc__)

 

3、

 创建装饰器, 要求如下:
# 1. 创建add_log装饰器, 被装饰的函数打印日志信息;
# 2. 日志格式为: [字符串时间] 函数名: xxx, 运行时间:xxx,
运行返回值结果:xxx
"""
import time
a = time.ctime()
print(a)

 

 

示例2:函数对修改是封闭的,对扩展是开放的

import time
def sec(fun):
    def add_info():
        a = time.time()
        fun()
        b=time.time()
        c = b - a
        print('时间差为:%.10f' %(c))
    return add_info
 
 
@sec
def f1():
    print(time.time())
    print('This is a function')
 
 
@sec
def f2():
    print(time.time())
    print('This is a function2')
 
f1()
f2()
 
执行结果:
/home/kiosk/PycharmProjects/westos6/venv/bin/python /home/kiosk/PycharmProjects/westos6/装饰器练习2.py
1554631396.7552593
This is a function
时间差为:0.0000474453
1554631396.7553174
This is a function2
时间差为:0.0000092983
 
Process finished with exit code 0

 

 

 

 

 

 

二 、多个装饰器

1、多个装饰器的定义

注意的是:当函数遇到多个装饰器时,执行顺序为,要添加函数外面的

代码执行顺序为从下到上,添加函数内部执行顺序为从下到上。

def decorator_a(fun):

    def inner_a(*args,**kwargs):
        print('Get in inner_a')
        fun(*args,**kwargs)
    return inner_a

def decorator_b(fun):

    def inner_b(*args,**kwargs):
        print('Get in inner_b')
        fun(*args,**kwargs)
    return inner_b

# 多个装饰器装饰函数 从上到下去执行的
@decorator_a
@decorator_b
def f(x):
    print('Gat in f')
f(1)

 

 

2、多个装饰器的应用

"""
['root','admin','redhat']
id+vip
多个装饰器的应用场景
会采用多个装饰器先验证是否登陆成功 再验证权限是否足够
"""
import inspect
login_session = ['root','admin','redhat']
import functools
def is_login(fun):
    @functools.wraps(fun)
    def warapper(*args,**kwargs):#('root',)
        if args[0] in login_session:
            temp = fun(*args,**kwargs)
            return temp
        else:
            print('Error:%s 没有登陆成功' %(args[0]))

    return warapper


def is_admin(fun):
    @functools.wraps(fun)
    #inspect_res 会返回一个字典
    # key:形参 value:对应的实参
    def wrapper(*args,**kwargs):
        inspect_res = inspect.getcallargs(fun,*args,**kwargs)
        print('inspect的返回值是:%s' %(inspect_res))
        if inspect_res.get('name') == 'root':
            temp = fun(*args,**kwargs)
            return temp

        else:
            print('not root user,no permisson add user')
    return wrapper

@is_login
@is_admin
def adduser(nam):
    print('add_user')

adduser('admin')

 

 

三、带参数的装饰器

1、基础版本的装饰器( 没有参数)

"""
 1. 基础版(无参数的装饰器)
# 编写装饰器required_ints, 条件如下:
#     1). 确保函数接收到的每一个参数都是整数;
#     2). 如果参数不是整形数, 打印 TypeError:参数必须为整形

"""
import functools
def required_ints(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):  # args=(1,2,..)
        for i in args:
            # if isinstance(i,int):
            #     pass
            # else:
            #     print('函数所有的参数并非都是int型')
            #     break
            if not isinstance(i, int):
                print('函数所有的参数并非都是int型')
                break
        else:
            res = func(*args, **kwargs)
            return res

    return wrapper
@required_ints
def add(a, b):
    return a + b
@required_ints
def mymax(a,b,c,d):
    return max(a,b,c,d)

print(add(1,2.0))

 

 

2、升级版的带有参数的装饰器

# 2. 升级版(有参数的装饰器)
# 编写装饰器required_types, 条件如下:
#     1). 当装饰器为@required_types(int,float)确保函数接收到的每一个参数都是
int或者float类型;
#     2). 当装饰器为@required_types(list)确保函数接收到的每一个参数都是list类型;
#     3). 当装饰器为@required_types(str,int)确保函数接收到的每一个参数都是str或者int类型;
#     4). 如果参数不满足条件, 打印 TypeError:参数必须为xxxx类型
#

"""

import functools
def required_type(*kinds):
    def required_int(fun):
        @functools.wraps(fun)
        def wropper(*args,**kwargs):
            for i in args:
                if not isinstance(i,kinds):
                    raise TypeError('参数必须为%s,%a'% kinds)
                else:
                    res = fun(*args,**kwargs)
                    return res
        return wropper
    return required_int
 
def add(a,b):
    return a + b
print(add('s','s'))


结果:
/opt/python3/bin/python3 /root/PycharmProjects/1127/文件.py
ss

Process finished with exit code 0

 

 

3、 带有一组数据的装饰器

import time
def decoator(fun):
    def  wropper(*args):
        print(time.time())
        fun(*args)
    return wropper
 
@decoator
def f1(fun_name):
    print('This is a function' + ' ' + fun_name)
 
@decoator
def f2(fun_name):
    print('This is a function' + ' ' + fun_name)
 
 
f1('1,2,3,4')
f2('4,5,6,7')
 
执行结果:
/home/kiosk/PycharmProjects/westos6/venv/bin/python /home/kiosk/PycharmProjects/westos6/含参数的装饰器.py
1554632121.0207565
This is a function 1,2,3,4
1554632121.0207922
This is a function 4,5,6,7
 
Process finished with exit code 0

 

 

4、包含多个参数和关键数参数的装饰器

import time
def  decortor(fun):
     def warrper(*args,**kwargs):
         print(time.time())
         fun(*args,**kwargs)
     return warrper
 
@decortor
def f1(function_name1,function_name2,**kwargs):
    print('This is a function' + '' + function_name1)
    print('This a function' + '' + function_name2)
    print(kwargs)
 
f1('test','test2',a=2,b=3,c=5)
 
执行结果:
/home/kiosk/PycharmProjects/westos6/venv/bin/python /home/kiosk/PycharmProjects/westos6/含关键字的装饰器.py
1554633214.0698268
This is a functiontest
This a functiontest2
{'a': 2, 'b': 3, 'c': 5}
 
Process finished with exit code 0

 

 

 

 

四、Python 中的第三方模块

示例1:第三方模块指的是别人写好的一些模块,可以实现一定的功能

实现给微信发送指定的内容

import random
import time
 
import itchat
 
itchat.auto_login()
 
while True:
 itchat.send('welcome use weixin',toUserName='filehelper')
 itchat.send_file('/etc/passwd',toUserName='filehelper')
 time.sleep(random.randint(1,3))
 
执行结果:
/home/kiosk/PycharmProjects/westos7/venv/bin/python /home/kiosk/PycharmProjects/westos7/第三方模快.py
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
Login successfully as 左手边

 

 

2、使用第三方模块实现统计微信中的好友

import random
import time
 
import itchat
 
itchat.auto_login()
 
friends = itchat.get_friends()
info = {}
 
for friend in friends[1:]:
    if friend['Sex'] == 1:
        info['male'] = info.get('male',0) + 1
    elif friend['Sex'] == 2:
        info['female'] = info.get('female',0) + 1
    else:
        info['other'] = info.get('other',0) + 1
 
print(info)
 
执行结果:
/home/kiosk/PycharmProjects/westos7/venv/bin/python /home/kiosk/PycharmProjects/westos7/第三方模快.py
Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.
Please press confirm on your phone.
Loading the contact, this may take a little while.
Login successfully as 左手边
{'male': 57, 'other': 11, 'female': 39}
 
Process finished with exit code 0

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值