zoukankan      html  css  js  c++  java
  • 元类

    引入

    一切都源自于一句话:一切皆为对象

    一、什么是元类?

    # 元类就是用来实例化产生类的类
    # 关系:元类---实例化---->类(People)---实例化---->对象(obj)
    class People:
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s:%s' %(self.name,self.name))
    
    
    # print(People.__dict__)
    # 如何得到对象
    # obj=调用类()
    # obj=People('egon',18)
    # print(type(obj))
    # 如果说类也是对象
    # People=调用类(。。。)
    
    # 查看内置的元类:
    # 1、type是内置的元类
    # 2、我们用class关键字定义的所有的类以及内置的类都是由元类type实例化产生
    print(type(People))
    print(type(int))
    

    二、class关键字创造类People的步骤

    # # 1、类名
    # class_name="People"
    # # 2、类的基类
    # class_bases=(object,)
    # # 3、执行类体代码拿到类的名称空间
    # class_dic={}
    # class_body="""
    # def __init__(self,name,age):
    #     self.name=name
    #     self.age=age
    #
    # def say(self):
    #     print('%s:%s' %(self.name,self.name))
    # """
    # exec(class_body,{},class_dic)
    # # print(class_dic)
    #
    # # 4、调用元类
    # People=type(class_name,class_bases,class_dic)
    

    三、如何自定义元类来控制类的产生

    class Mymeta(type): # 只有继承了type类的类才是元类
        #            空对象,"People",(),{...}
        def __init__(self,x,y,z):
            print('run22222222222....')
            print(self)
            print(x)
            print(y)
            print(z)
            print(y)
            if not x.istitle():
                raise NameError('类名的首字母必须大写啊!!!')
    
    #     #          当前所在的类,调用类时所传入的参数
        def __new__(cls, *args, **kwargs):
            # 造Mymeta的对象
            print('run1111111111.....')
            # print(cls,args,kwargs)
            # return super().__new__(cls,*args, **kwargs)
            return type.__new__(cls,*args, **kwargs)
    
    
    # # People=Mymeta("People",(object,),{...})
    # # 调用Mymeta发生三件事,调用Mymeta就是type.__call__
    # # 1、先造一个空对象=>People,调用Mymeta类内的__new__方法
    # # 2、调用Mymeta这个类内的__init__方法,完成初始化对象的操作
    # # 3、返回初始化好的对象
    #
    class People(metaclass=Mymeta):
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s:%s' %(self.name,self.name))
    
    # # 强调:
    # # 只要是调用类,那么会一次调用
    # # 1、类内的__new__
    # # 2、类内的__init__
    

    四、call_

    class Foo:
        def __call__(self, *args, **kwargs):
            print(self)
            print(args)
            print(kwargs)
    
    obj=Foo()
    #1、要想让obj这个对象变成一个可调用的对象,需要在该对象的类中定义一个方法__call__方法,该方法会在调用对象时自动触发
    #2、调用obj的返回值就是__call__方法的返回值
    res=obj(1,2,3,x=1,y=2)
    
    # 总结:
    # 对象()->类内的__call__
    # 类()->自定义元类内的__call__
    # 自定义元类()->内置元类__call__
    

    五、自定义元类控制类的调用=》类的对象的产生

    class Mymeta(type): # 只有继承了type类的类才是元类
        def __call__(self, *args, **kwargs):
            # 1、Mymeta.__call__函数内会先调用People内的__new__
            people_obj=self.__new__(self)
            # 2、Mymeta.__call__函数内会调用People内的__init__
            self.__init__(people_obj,*args, **kwargs)
    
            # print('people对象的属性:',people_obj.__dict__)
            people_obj.__dict__['xxxxx']=11111
            # 3、Mymeta.__call__函数内会返回一个初始化好的对象
            return people_obj
    
    # 类的产生
    # People=Mymeta()=》type.__call__=>干了3件事
    # 1、type.__call__函数内会先调用Mymeta内的__new__
    # 2、type.__call__函数内会调用Mymeta内的__init__
    # 3、type.__call__函数内会返回一个初始化好的对象
    
    class People(metaclass=Mymeta):
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s:%s' %(self.name,self.name))
    
        def __new__(cls, *args, **kwargs):
            # 产生真正的对象
            return object.__new__(cls)
    
    # 类的调用
    # obj=People('egon',18) =》Mymeta.__call__=》干了3件事
    # 1、Mymeta.__call__函数内会先调用People内的__new__
    # 2、Mymeta.__call__函数内会调用People内的__init__
    # 3、Mymeta.__call__函数内会返回一个初始化好的对象
    
    obj1=People('egon',18)
    obj2=People('egon',18)
    # print(obj)
    print(obj1.__dict__)
    print(obj2.__dict__)
    
    {'name': 'egon', 'age': 18, 'xxxxx': 11111}
    {'name': 'egon', 'age': 18, 'xxxxx': 11111}
    

    六、属性查找

    在学习完元类后,其实我们用class自定义的类也全都是对象(包括object类本身也是元类type的 一个实例,可以用type(object)查看),我们学习过继承的实现原理,如果把类当成对象去看,将下述继承应该说成是:对象StanfordTeacher继承对象Foo,对象Foo继承对象Bar,对象Bar继承对象object

    class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
        n=444
    
        def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
            obj=self.__new__(self)
            self.__init__(obj,*args,**kwargs)
            return obj
    
    class Bar(object):
        n=333
    
    class Foo(Bar):
        n=222
    
    class StanfordTeacher(Foo,metaclass=Mymeta):
        n=111
    
        school='Stanford'
    
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s says welcome to the Stanford to learn Python' %self.name)
    
    
    print(StanfordTeacher.n) #自下而上依次注释各个类中的n=xxx,然后重新运行程序,发现n的查找顺序为StanfordTeacher->Foo->Bar->object->Mymeta->type
    

    于是属性查找应该分成两层,一层是对象层(基于c3算法的MRO)的查找,另外一个层则是类层(即元类层)的查找

    对象查找

    #查找顺序:
    #1、先对象层:StanfordTeacher->Foo->Bar->object
    #2、然后元类层:Mymeta->type
    

    依据上述总结,我们来分析下元类Mymeta中__call__里的self.__new__的查找

    class Mymeta(type): 
        n=444
    
        def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
            obj=self.__new__(self)
            print(self.__new__ is object.__new__) #True
    
    
    class Bar(object):
        n=333
    
        # def __new__(cls, *args, **kwargs):
        #     print('Bar.__new__')
    
    class Foo(Bar):
        n=222
    
        # def __new__(cls, *args, **kwargs):
        #     print('Foo.__new__')
    
    class StanfordTeacher(Foo,metaclass=Mymeta):
        n=111
    
        school='Stanford'
    
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s says welcome to the Stanford to learn Python' %self.name)
    
    
        # def __new__(cls, *args, **kwargs):
        #     print('StanfordTeacher.__new__')
    
    
    StanfordTeacher('lili',18) #触发StanfordTeacher的类中的__call__方法的执行,进而执行self.__new__开始查找
    

    总结,Mymeta下的__call__里的self.new__在StanfordTeacher、Foo、Bar里都没有找到__new__的情况下,会去找object里的__new,而object下默认就有一个__new__,所以即便是之前的类均未实现__new__,也一定会在object中找到一个,根本不会、也根本没必要再去找元类Mymeta->type中查找__new__

    我们在元类的__call__中也可以用object.new(self)去造对象

    但我们还是推荐在__call__中使用self.new(self)去创造空对象,因为这种方式会检索三个类StanfordTeacher->Foo->Bar,而object.__new__则是直接跨过了他们三个

    class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类
        n=444
    
        def __new__(cls, *args, **kwargs):
            obj=type.__new__(cls,*args,**kwargs) # 必须按照这种传值方式
            print(obj.__dict__)
            # return obj # 只有在返回值是type的对象时,才会触发下面的__init__
            return 123
    
        def __init__(self,class_name,class_bases,class_dic):
            print('run。。。')
    
    
    class StanfordTeacher(object,metaclass=Mymeta): #StanfordTeacher=Mymeta('StanfordTeacher',(object),{...})
        n=111
    
        school='Stanford'
    
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s says welcome to the Stanford to learn Python' %self.name)
    
    
    print(type(Mymeta)) #<class 'type'>
    # 产生类StanfordTeacher的过程就是在调用Mymeta,而Mymeta也是type类的一个对象,那么Mymeta之所以可以调用,一定是在元类type中有一个__call__方法
    # 该方法中同样需要做至少三件事:
    # class type:
    #     def __call__(self, *args, **kwargs): #self=<class '__main__.Mymeta'>
    #         obj=self.__new__(self,*args,**kwargs) # 产生Mymeta的一个对象
    #         self.__init__(obj,*args,**kwargs) 
    #         return obj
    ```![](https://img2020.cnblogs.com/blog/1865512/202004/1865512-20200415195753650-1425788146.jpg)
  • 相关阅读:
    2016-12-31:最后一天:回顾
    ubuntu-15.10-server-i386.iso 安装 Oracle 11gR2 数据库
    ubuntu-15.04-server-i386.iso 安装 Oracle 11gR2 数据库
    ubuntu-16.04+-xxx-i386.iso :安装 Oracle 11gR2 数据库
    VirtualBox 所有版本的下载地址:http://download.virtualbox.org/virtualbox/
    上海医保每年注入时间
    打新股
    check system version
    add, subtract, multiply, divide
    WRITE T AFTER ADVANCING 2 LINES
  • 原文地址:https://www.cnblogs.com/chenyoupan/p/12707629.html
Copyright © 2011-2022 走看看