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

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-29
  • 2022-12-23
  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
  • 2022-03-05
猜你喜欢
  • 2021-07-31
  • 2022-02-15
  • 2021-10-13
  • 2022-12-23
  • 2022-12-23
  • 2021-09-12
相关资源
相似解决方案