zoukankan      html  css  js  c++  java
  • python 元类型编程,实现匿名验证器的装饰器AuthenticationDecoratorMeta

    metaclass,元类

    metaclass是这样定义的:In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances.

    metaclass的实例化结果是类,而class实例化的结果是instance。metaclass是创建类的模板,所有的类都是通过他来create的(调用__new__),你可以定创建类的独特行为,实现你所需要的特殊功能。

    type 也是metalclass的一种元类。

    通过派生type的子类,来实现类创建过程中的特殊行为。

    type的构造函数:type.__new__(cls, name, bases, dct)

    • cls: 将要创建的类,类似与self,但是self指向的是instance,而这里cls指向的是class
    • name: 类的名字
    • bases: 基类,通常是tuple类型
    • attrs: dict类型,就是类的属性或者函数

    实现为类的方法,进行匿名验证的metaclass, ----AuthenticationDecoratorMeta

    源码:

    from types import FunctionType
    
    def Authentication(func):
        print 'Execute validition Successfully!'
        return func
    
    class AuthenticationDecoratorMeta(type):
        def __new__(cls, name, bases, dct):
            for name, value in dct.iteritems():
                if name not in ('__metaclass__', '__init__', '__module__') and \
                type(value) == FunctionType:
                    value = Authentication(value)
                dct[name] = value
            return type.__new__(cls, name, bases, dct)
        
    class Login(object):
        __metaclass__ = AuthenticationDecoratorMeta
        
        def Delete(self, x):
            print 'Delete ', x
    
    def main():
        login = Login()
        login.Delete('xxxx')    
    if __name__ == '__main__':  
        main()  

    运行效果如下:

    Execute validition Successfully!
    Delete  xxxx

     

  • 相关阅读:
    寒假练习集中贴
    7-49 打印学生选课清单 (25分)
    7-47 打印选课学生名单 (25分)
    进阶实验5-3.3 基于词频的文件相似度 (30分)-哈希
    进阶实验5-3.4 迷你搜索引擎 (35分)-哈希
    7-24 树种统计 (25分)-二叉排序树or快速排序
    7-25 朋友圈 (25分)-并查集
    进阶实验6-3.4 拯救007(升级版) (30分)-BFS
    基础实验6-2.3 拯救007 (25分)-DFS
    进阶实验4-3.5 哈夫曼编码 (30分)-最优二叉树
  • 原文地址:https://www.cnblogs.com/ankier/p/2831503.html
Copyright © 2011-2022 走看看