Python正课83 —— 属性查找 - 进阶

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12708369.html

一:属性查找的原则:对象 ==> 类 ==> 父类

切记:父类 不是 元类

切记:父类 不是 元类

切记:父类 不是 元类

二:例子

class Mymeta(type):
    n=444

    def __call__(self, *args, **kwargs): #self=<class '__main__.StanfordTeacher'>
        obj=self.__new__(self) # 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__')
    pass

class Foo(Bar):
    # n=222

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

class StanfordTeacher(Foo,metaclass=Mymeta):
    # n=111

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


obj=StanfordTeacher('lili',18)
print(obj.__dict__)
# print(obj.n)
# print(StanfordTeacher.n)
posted @ 2020-04-15 20:56  轻描丨淡写  阅读(217)  评论(0编辑  收藏  举报