元类的描述

所有类都是元类的对象

class Foo:
    pass

print(type(Foo))  #<class 'type'>

定义类的2种方式:

1.

第一种就是正常的用class来定义

2.

Foo=type("Foo",(object,),{"x":1})

type的三个参数:

  1.类名

  2.继承的类

  3.类的属性

 

 

下面来看自定义元类,自定义元类都得继承type

class Foo1:
    pass
class Type(type):
    def __init__(self,a,b,c):
        print("我是元类")
        print(a)
        print(b) #self继承的父类
        print(c)  #self.__dict__
    def __call__(self, *args, **kwargs):
        res=object.__new__(self) #self=Foo  object.__new__(self)==>Foo()
        self.__init__(res,*args,**kwargs)
        return res

class Foo(Foo1,metaclass=Type,):  # Foo=Type(Foo,"Foo",(),{})
    def __init__(self,name):
        self.name=name
    def test(self):
        pass
f=Foo("w")
print(f.name)
print(Foo.__dict__)

运行Foo()就是运行Type中的__call__方法

posted @ 2020-07-11 14:59  彡心如止水彡  阅读(122)  评论(0)    收藏  举报