面向对向之元类

一、什么是元类?

一切源于,一名话,一切皆对对象。

class StanfordTeacher(object):
    school = 'Standford'
    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)

  所有的对象都是实例化或都说调用类而得到的(调用类的过程称为类的实例化),比如对象t1是调用类StanfordTeach得到的

t1 = StanfordTeacher('egon',18)
print (type(t1))

  如果一切皆为对象,那么类StanfordTeacher本质也是一个对象,既然所有的对象都是调用类得到的,那么StanfordTeachernt 必然也是调用了一个类得到的,这个类称为元类。

二、class关键字创建类的流程分析

class关键字定义的类本身也是一个对象,负责产生该对象的类称之为元类(元类可以简称为类的类),内置的元类为type

class关键字在帮我们创建类时,必然帮我们调用了元类StanfordTeacher=type()

一个类有三大组成部分:

1、类名class_name = "StanfordTeacher'

2、基类们class_bases=(object,)

3、类的名称空间class_dic,类的名称空间是执行类体代码而得到的调用type时会依次传入以上三个参数

 

class帮我们创建类时执行了以下四步:

1、拿到类名

2、拿到类的基类们

3、执行类体代码,拿到类的名称空间

4、调用元类得到类

 

三、自定义元类控制类StanfordTeacher的创建

一个类没有声明自己的元类,默认他的元类就是type,除了使用内置元类type,我们也可以通过继承type来自定义元类,然后使用metaclass关键字参数为一个类指定元类

class Mymeta(type):
    pass                 #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类

class StanfordTeacher(object,metaclass=Mymeta):
    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)

 自定义元类可以控制类的产生过程,类的产生过程其实就是元类的调用过程

五、自定义元类近控制类StanfordTeacher的调用

__call__   要想让obj对象变成一个可调用的对象,需要在该对象的类中定义一个方法就是__call__方法,该方法会在调用对象时自动触发

class Foo:
    def __call__(self,*args,**kwargs):
        print (self)
        print(args)
        print(kwargs)

obj = Foo()
#调用obj的返回值就是__call__方法的返回值
res=obj(1,2,3,x=1,y=2)

  调用一个对象,就是触发对象所在类中的__call__方法的执行,如果把StanfordTeacher也当做一个对象,那么在StandfordTeacher这个对象的类中也必然存在一个__call__方法

 

默认地,调用t1= StafordTeacher('egon',18)会做三件事

1、产生一个空对象obj

2、调用__init__方法初始化对象obj

3、返回初始化好的obj

对应着,StanfordTeacher类中的__call__方法也应该做这三件事

 

六、属性查找

我们学习过继承的实现原理,如果把类当成对象去看,将下述继承应该说成是:对象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

  

StanfordTeacher ——> Foo ------>Bar------->object------>Mymeta 

     先对象层                                                                     再元类层

 

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__

 

 

 

 

 

 

 

 

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__开始查找
posted @ 2020-04-15 19:34  anna2019  阅读(164)  评论(0编辑  收藏  举报