Day33.元类下的属性查找

1.元类下的属性查找_对象.方法和类名.方法的查找经过

# todo 属性查找的原则: 对象 -> 类 -> 父类
# todo 切记: 父类 不是 元类

class Mymeta(type): 
    n=444
    def __call__(self, *args, **kwargs): # self=<class '__main__.StanfordTeacher'>
        obj=self.__new__(self)      # todo StanfordTeacher.__new__
        # obj = object.__new__(self)
        print(self.__new__ is object.__new__) # True
        self.__init__(obj, *args, **kwargs)
        return obj


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
    def __init__(self,name,age):
        self.name=name
        self.age=age

    # def __new__(cls, *args, **kwargs):
    #     print('StanfordTeacher.__new__')

obj = StanfordTeacher('lili',18)    # todo 触发StanfordTeacher的类中的__call__方法的执行,进而执行self.__new__开始查找
print(obj.n)                # todo `对象.方法`继承的父类找不到会直接报错
print(StanfordTeacher.n)    # todo `类型.方法`继承的父类找不到会在元类中查找

 

posted on 2024-07-15 14:19  与太阳肩并肩  阅读(1)  评论(0编辑  收藏  举报

导航