美文网首页
Python 装饰器简单理解

Python 装饰器简单理解

作者: 热血大桃子 | 来源:发表于2018-08-22 16:09 被阅读0次

装饰器的作用

 首先来理解一下装饰器的作用:扩展原函数的功能。使用装饰器的一个好处就是能够不改变原函数代码同时还能提供新的功能,先举个一个简单例子来加深理解。
 我们现在有一个函数func,主要干的事情就是打印“hello world”并暂停1秒:

import time
def func():
   print("hello world")
   time.sleep(1)

 这个时候如果我们要扩展此函数的功能,比如我要计算一下这个函数耗时,一般来说我们是直接在原代码中直接添加相应的代码:

import time
def func():
    start = time.time()
    print("hello world")
    time.sleep(1)
    end = time.time()
    print('cost time %s' % (end - start))

 假设这个函数灰常灰常重要,而我又是个菜鸡coder,又不敢瞎改,有什么办法呢?嘿,脑子灵机一动,写个函数把要加的功能先实现了,然后函数里面调用func()不就好了嘛,就成下面这样:

import time
def func():
    print("hello world")
    time.sleep(1)

def func2(func):
    start = time.time()
    func()
    end = time.time()
    print('cost time %s' % (end - start))

if __name__ == '__main__':
    func2(func)

 咳咳咳,真是机智的小鬼啊。可是假设我已经写了好几十万行代码,并且里面有数不清的地方调用了func函数,现在的新需求是添加一个耗时计算打印的功能,按照上面的做法,我要花很多时间去找到调用func()的地方,并将代码改成func2(),然而你一个月的时间都花在了这个工作上面,老板说我没有效率,要开除我... ... 这个时候该怎么办呢?于是脑子又灵光一闪,有了:

import time
def decorator(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print('decorator cost time %s' % (end - start))

    return wrapper

@decorator
def func():
    print("hello world")
    time.sleep(1)

if __name__ == '__main__':
    func()

 这样我就不用去花一个月的时间修改所有func(),依然保留原有代码,并且还添加了新的功能,hhh真是个天才。如果函数要带有参数(一个两个三个、、、到若干个),那么可以这样:

import time
def decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print('decorator cost time %s' % (end - start))

    return wrapper

@decorator
def func(*args, **kwargs):
    print("hello world", args[0],args[1])
    time.sleep(1)

if __name__ == '__main__':
    func(1, 2)

 噢,对了,装饰器可以多个,就像下面这样:

import time
def decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print('decorator cost time %s' % (end - start))

    return wrapper

def decorator2(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print('decorator2 cost time %s' % (end - start))

    return wrapper

@decorator
@decorator2
def func(*args, **kwargs):
    print("hello world", args[0],args[1])
    time.sleep(1)

if __name__ == '__main__':
    func(1, 2)

 它的启动顺序是离函数越近的先启动,比如上面就先启动decorator2,然后是decorator。
 好了,差不多初步掌握装饰器是啥东西了也能简单的运用了。

新更新一些装饰器的实际作用

 我们先看代码:

from functools import wraps
class OverrideException(Exception):
    """
    重写类变量异常
    """

# 防止类变量被重写
def Const(cls):
    @wraps(cls)
    def new_setattr(self, name, value):
        raise OverrideException('const : {} can not be changed'.format(name))
    cls.__setattr__ = new_setattr
    return cls

@Const
class A(object):
    rich = 'rich'

a = A()
a.rich = 1
print(w.rich)

 简单说一下是怎么实现 “防止类变量被重写” 的功能的。我们在为实例a的变量赋值时,会调用类方法___setattr____(*args, **kwargs),在上面代码中我们在new_setattr()方法中抛出异常,并将____setattr____重写,这个时候通过装饰器,就能保护的你想要保护的类属性不被修改。注意Const(cls)中的cls就是我们的类A,注重写的是类A的____setattr____。

相关文章

  • Python 装饰器简单理解

    装饰器的作用  首先来理解一下装饰器的作用:扩展原函数的功能。使用装饰器的一个好处就是能够不改变原函数代码同时还能...

  • 2019-05-26python装饰器到底是什么?

    装饰器例子 参考语法 装饰器是什么?个人理解,装饰器,是python中一种写法的定义。他仍然符合python的基本...

  • Python中的Decorator装饰器

    Decorator 装饰器 理解decorator(装饰器)的关键, 在于理解在python中函数是第一公民, 并...

  • Python装饰器的简单理解

    没别的意思,稍微记录一下Python装饰器的简单理解 对Python语法尤其是对函数式编程不太熟悉的话可能理解Py...

  • python 装饰器 补充

    重新理解python 装饰器 python 装饰器是一个函数,被装饰器所装饰的代码块最终也是一个函数这个对于一般的...

  • python装饰器

    装饰器简述 要理解装饰器需要知道Python高阶函数和python闭包,Python高阶函数可以接受函数作为参数,...

  • Python学习资料整理(不间断更新)

    关于Python装饰器的相关文章资料 1、[翻译]理解PYTHON中的装饰器 本篇文章是作者翻译stackover...

  • python 装饰器

    一、我们在python语言中常用@classmethod、@staticmethod这个装饰器,装饰器的作用简单来...

  • 9个Python 内置装饰器: 显著优化代码

    装饰器是应用“Python 之禅”哲学的最佳 Python 特性。装饰器可以帮助您编写更少、更简单的代码来实现复杂...

  • Python装饰器小谈

    近几日再次研究Python装饰器,对装饰器又有了新的理解和应用。如果这篇文章叫做小谈装饰器,不如重谈装饰器更来得亲...

网友评论

      本文标题:Python 装饰器简单理解

      本文链接:https://www.haomeiwen.com/subject/culyiftx.html