class Foo:
pass
f=Foo()
print(type(f1)) #f1是通过Foo类实例化的对象
print(type(Foo)) #Foo是通过type类实例化的对象
print('===================>')
class Foo1:
x=1
def __init__(self,name,age):
self.name=name
self.age=age
def test(self):
pass
print(Foo1.__dict__)
f1=Foo1('mcc',11)
def __init__(self,name,age):
self.name=name
self.age=age
def test(self):
print("=========>")
Foo2=type('Foo2',(object,),{'x':1,'__init__':__init__,'test':test})
print(Foo2.__dict__)
f2=Foo2('zcc',12)
元类type实例化(Foo,Foo1,Foo2)三个对象,同时这三个类又分别实例化(f,f1,f2)三个对象
实际应用:
class MyType(type):
def __init__(self,a,b,c):
pass
# print(a)
# print(b)
# print(c)
def __call__(self, *args, **kwargs):
print('====>')
print(self)
obj=object.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class Foo(metaclass=MyType):#MyType(Foo,'Foo',(object,),'__init__':__init__)
def __init__(self,name,age):
self.name=name
self.age=age
f3=Foo('alan',12)
print(f3.__dict__)