python装饰器高级用法

1.装饰类

  下面,直接来看代码是如何实现装饰类的:

def decorator(aClass):
    class newClass:
        def __init__(self, age):
            self.total_display   = 0
            self.wrapped         = aClass(age)
        def display(self):
            self.total_display += 1
            print("total display", self.total_display)
            self.wrapped.display()
    return newClass

@decorator # 接受一个类参数
class Bird:
    def __init__(self, age):
        self.age = age
    def display(self):
        print("My age is",self.age)

eagleLord = Bird(5)
for i in range(3):
    eagleLord.display()

  在decorator中,我们返回了一个新类newClass。在新类中,我们记录了原来类生成的对象(self.wrapped),并附加了新的属性total_display,用于记录调用display的次数。我们也同时更改了display方法。

  通过修改,我们的Bird类可以显示调用display的次数了

2.装饰器捕捉异常

  有一个check类,其中有方法read_value()。由于某些原因,方法read_value有可能抛出异常而使程序崩溃,所以需要对整个方法做try....except处理,如:

  没有捕捉异常之前:

class check(object):
    def __init__(self):
        pass

    def receive(self):
        print(‘receive from exception.‘)

    def read_value(self):
        print(‘here i will do something‘)
        ‘a‘ + 1  # 这里会报异常

c = check()
c.read_value()

  加了try....except捕捉异常后:

class check(object):
    def __init__(self):
        pass

    def receive(self):
        print(‘receive from exception.‘)

    def read_value(self):
        try:
            print(‘here i will do something‘)
            ‘a‘ + 1
        except Exception as e:
            print(e)

c = check()
c.read_value()

  虽然程序不会报出异常,但这样处理,有些丑陋。来看看装饰器是如何处理的:

def catch_exception(func):
    def wrapper(*args,**kwargs):
        try:
            u = func(*args,**kwargs)
            return u
        except Exception:
            return ‘an exception raised‘
    return wrapper

class check(object):
    def __init__(self):
        pass

    def receive(self):
        print(‘receive from exception.‘)

    @catch_exception
    def read_value(self):
        print(‘here i will do something‘)
        ‘a‘ + 1

c = check()
c.read_value()

  很好,使用装饰器,来装饰函数,这样使我们的代码更加pythonic。但是,如果程序报出异常后,调用类中的另外一个方法,那怎么办?很简单,给装饰器加上一个参数self:

def catch_exception(func):
    def wrapper(self,*args,**kwargs):
        try:
            u = func(self,*args,**kwargs)
            return u
        except Exception:
            self.receive()
            return ‘an exception raised‘
    return wrapper
class check(object):
    def __init__(self):
        pass

    def receive(self):
        print(‘receive from exception.‘)

    @catch_exception
    def read_value(self):
        print(‘here i will do something‘)
        ‘a‘ + 1

c = check()
c.read_value()

  有木有感觉,很神奇。

时间: 2024-08-25 12:41:36

python装饰器高级用法的相关文章

python 装饰器的用法

为什么要使用装饰器? 在不改变原函数功能的情况,为了添加新的功能 我们可以在函数运行前后给函数添加新的功能 1 def outer(func): 2 #fun()等于原f1函数 3 def inner(): 4 print('ccccc') 5 r=func() 6 print('dddd') 7 return r 8 return inner 9 @outer 10 #@outer代表运行了2个步骤:1.将f1作为参数运行outer函数,2.新函数f1=inner() 11 def f1():

Python装饰器主要用法

#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = '人生入戏' user = "admin" passwd = "123456" def auth(auth_type): #print("auth_type:",auth_type) def out_wrapper(func): #print("func",func) def wrapper(*args,**

python装饰器的用法

def logger(func): def inner(*args, **kwargs): #1 print "Arguments were: %s, %s" % (args, kwargs) return func(*args, **kwargs) #2 return inner >>> @logger ... def foo1(x, y=1): ...     return x * y >>> @logger ... def foo2(): ..

Python装饰器的另类用法

之前有比较系统介绍过Python的装饰器,本文算是一个补充.今天我们一起探讨一下装饰器的另类用法. 语法回顾 开始之前我们再将Python装饰器的语法回顾一下. @decorate def f(...): pass 等同于: def f(...): pass f = decorate(f) @语法的好处在于: 相同的函数名只出现一次,避免了f = decorate(f)这样的语句. 可读性更高,让读代码的人一眼就明白函数被装饰了哪些功能. @call()装饰器 假设你要创建一个整数平方的列表,你

Python装饰器由浅入深

装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们以装饰函数为例子介绍其用法.要理解在Python中装饰器的原理,需要一步一步来.本文尽量描述得浅显易懂,从最基础的内容讲起. (注:以下使用Python3.5.1环境) 一.Python的函数相关基础 第一,必须强调的是python是从上往下顺序执行的,而且碰到函数的定义代码块是不会立即执行它的,只

Python——装饰器基础

装饰器基础 前面快速介绍了装饰器的语法,在这里,我们将深入装饰器内部工作机制,更详细更系统地介绍装饰器的内容,并学习自己编写新的装饰器的更多高级语法. ================================================================================= 什么是装饰器 装饰是为函数和类指定管理代码的一种方式.Python装饰器以两种形式呈现: [1]函数装饰器在函数定义的时候进行名称重绑定,提供一个逻辑层来管理函数和方法或随后对它们的调

Python装饰器详解,详细介绍它的应用场景

装饰器的应用场景 附加功能 数据的清理或添加: 函数参数类型验证 @require_ints 类似请求前拦截 数据格式转换 将函数返回字典改为 JSON/YAML 类似响应后篡改 为函数提供额外的数据 mock.patch 函数注册 在任务中心注册一个任务 注册一个带信号处理器的函数 不同应用场景下装饰器实现 函数注册表 简单注册表 funcs = [] def register(func): funcs.append(func) return func @register def a(): r

5.初识python装饰器 高阶函数+闭包+函数嵌套=装饰器

一.什么是装饰器? 实际上装饰器就是个函数,这个函数可以为其他函数提供附加的功能. 装饰器在给其他函数添加功能时,不会修改原函数的源代码,不会修改原函数的调用方式. 高阶函数+函数嵌套+闭包 = 装饰器 1.1什么是高阶函数? 1.1.1函数接收的参数,包涵一个函数名. 1.1.2 函数的返回值是一个函数名. 其实这两个条件都很好满足,下面就是一个高阶函数的例子. def test1(): print "hamasaki ayumi" def test2(func): return t

深入浅出 Python 装饰器:16 步轻松搞定 Python 装饰器

Python的装饰器的英文名叫Decorator,当你看到这个英文名的时候,你可能会把其跟Design Pattern里的Decorator搞混了,其实这是完全不同的两个东西.虽然好像,他们要干的事都很相似--都是想要对一个已有的模块做一些"修饰工作",所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去.但是OO的Decorator简直就是一场恶梦,不信你就去看看wikipedia上的词条