元类补充-属性查找

 查找顺序:
一切皆对象,把Foo,B,A都看成对象
先在对象层找,如果对象层没有,再去元类层找,先Mymeta,再type
1、先对象层:Foo->B->A->object
2、然后元类层:Mymeta->type
class Mymeta(type):
    n = 444

    def __call__(self, *args, **kwargs):
        obj = self.__new__(self)  # self=Foo
        self.__init__(obj, *args, **kwargs)
        return obj


class A(object):
    n = 333


class B(A):
    n = 222


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

    def __init__(self, x, y):
        self.x = x
        self.y = y


print(Foo.n)
print(type(object))
obj = Foo(1, 2)
print(obj.__dict__)  # {"x":1,"y":2}

  

猜你喜欢

转载自www.cnblogs.com/Roc-Atlantis/p/9254163.html