metaclass 元类
元类是类的类,是类的模版。
元类是用来控制如何创建类的,正如类是创建对象的模版一样
元类的实例为类。
type事python的一个内建元类,用来直接控制生成类,python中任何class定义的类其实都是type类实例化的对象。
class Foo: pass f1=Foo() #f1是通过Foo类实例化的对象 print(type(f1))#用type函数查看是谁的类 print(type(Foo))#类的类就是type def __init__(self,name,age):#如果需要再type中增加构造函数,就需要将函数放到最外面 self.name=name self.age=age FFo=type(‘FFo‘,(object,),{‘x‘:1,‘__init__‘:__init__}) #用type生成类,第一个事类名,第二个元祖形式是父类,因为是新式类所以父类默认就是object,后面是用字典形式表达参数 print(FFo) f1=FFo(‘SXJ‘,11) print(f1.__dict__)
>>>>
<class ‘__main__.Foo‘>
<class ‘type‘>
<class ‘__main__.FFo‘>
{‘name‘: ‘SXJ‘, ‘age‘: 11}
原文:https://www.cnblogs.com/python1988/p/11623105.html