有了元类之后的属性查找顺序

查找顺序(代码)

类的属性查找顺序: 先从类自身找---->mro继承关系去父类中找---->去自己定义的元类中找---->type中---->报错

对象的属性查找顺序: 先从对象自身找---->去类中找---->mro继承关系去父类中找----->报错

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

    def __call__(self, *args, **kwargs):  # self=<class '__main__.OldboyTeacher'>
        obj = self.__new__(self)
        self.__init__(obj, *args, **kwargs)
        return obj

class Bar(object):
    n = 333

class Foo(Bar):
    n = 222

class OldboyTeacher(Foo, metaclass=Mymeta):
    n = 111

    school = 'oldboy'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say(self):
        print('%s says welcome to the oldboy to learn Python' % self.name)

print(OldboyTeacher.n)  # 自下而上依次注释各个类中的n=xxx,然后重新运行程序,发现n的查找顺序为OldboyTeacher->Foo->Bar->object->Mymeta->type

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

posted @ 2023-10-30 11:22  hanyingshuo  阅读(10)  评论(0)    收藏  举报