zoukankan      html  css  js  c++  java
  • Python 类的装饰器

    基于类的装饰器,思路跟基于函数的装饰器类似,但是需要注意类中的 getattr return

    下面看一个示例:

    def authentication(func):
    
        class Auth(object):
    
            def __init__(self, *args, **kwargs):
                print("Pre-Authentication")
                self.func = func(*args, **kwargs)
                print("Post-Authentication")
    
            def __getattr__(self, item):
                return getattr(self.func, item)
    
        return Auth
    
    
    @authentication
    class A(object):
        """
        测试类 A,用于各种类的功能测试。
        """
    
        def __init__(self, name):
            print("I Init: " + name)
            self.name = name
    
        def say(self):
            print("I Love: " + self.name)
    
    
    if __name__ == '__main__':
        a = A("Python")
        a.say()


    >> 执行结果

      Pre-Authentication
      I Init: Python
      Post-Authentication
      I Love: Python

    本文章参考了ggGavin的 编写类装饰器

    未完待续......

  • 相关阅读:
    asp.net微信开发第八篇----永久素材管理
    selenium模块
    request模块
    爬虫基本概念
    反向生成url
    admin的路由系统剖析
    popup方法
    ModelForm
    Django数据库操作性能相关
    缓存
  • 原文地址:https://www.cnblogs.com/vincenshen/p/6420726.html
Copyright © 2011-2022 走看看