创建类的两种方式
方式一:class Foo(object,metaclass=type): CITY = "bj" def func(self,x): return x + 1方式二:Foo = type('Foo',(object,),{'CITY':'bj','func':lambda self,x:x+1})
类的演变
演变1:class MyType(type): def __init__(self,*args,**kwargs): print('创建类之前') super(MyType,self).__init__(*args,**kwargs) print('创建类之后')Base = MyType('Base',(object,),{})# class Base(object,metaclass=MyType):# passclass Foo(Base): CITY = "bj" def func(self, x): return x + 1演变2:class MyType(type): def __init__(self,*args,**kwargs): print('创建类之前') super(MyType,self).__init__(*args,**kwargs) print('创建类之后')def with_metaclass(arg): return MyType('Base',(arg,),{}) # class Base(object,metaclass=MyType): passclass Foo(with_metaclass(object)): CITY = "bj" def func(self, x): return x + 1演变3:class MyType(type): def __init__(self,*args,**kwargs): super(MyType,self).__init__(*args,**kwargs)class Foo(object,metaclass=MyType):
总结
1. 默认类由type实例化创建。2. 某个类指定metaclass=MyType,那么当前类的所有派生类都由于MyType创建。3. 实例化对象 - type.__init__ - type.__call__ - 类.__new__ - 类.__init__