Python中的数据模型
__new__ 与 __init__ 的区别
- __new__在__init__之前调用
- __new__在返回一个类的实例时,会调用类的__init__函数
- __new__没有返回类的实例,或者返回的实例对应的类没有__init__,则不会调用__init__
- type与object作为父类的区别
- metaclass定义父类的含义
type.new() --> classobject.new() --> instance
metaclass定义 metaclass.new --> metaclass.init --> class.new --> class.init
class Meta(type):
def __init__(self, name, bases, ns, **kwds):
print('Meta.init', self)
def __new__(self, name, bases, ns, **kwds):
print('Meta.new', self, name, bases, ns, kwds)
return super().__new__(self,name, bases, dict(ns))
## return type.__new__(self)
class Test(metaclass=Meta):
def __init__(self):
print('Test.init', self)
def __new__(self, *args, **kwds):
print('Test.new', self)
return super().__new__(self)
t = Test()
print('='*20)
class Meta(type):
def __init__(self, name, bases, ns, **kwds):
print('Meta.init', self)
def __new__(self, name = 'Test', bases= (), ns=[], **kwds):
print('Meta.new', self, name, bases, ns, kwds)
return super().__new__(self,name, bases, dict(ns))
## return type.__new__(self)
class Test(Meta):
def __init__(self):
print('Test.init', self)
def __new__(self, *args, **kwds):
print('Test.new', self)
return super().__new__(self)
t = Test()
print('='*20)
class Meta(object):
def __init__(self, name, bases, ns, **kwds):
print('Meta.init', self)
def __new__(self, name = 'Test', bases= (), ns=[], **kwds):
print('Meta.new', self, name, bases, ns, kwds)
return super().__new__(self)
class Test(Meta):
def __init__(self):
print('Test.init', self)
def __new__(self, *args, **kwds):
print('Test.new', self)
return super().__new__(self)
t = Test()
print('='*20)
class Meta(object):
def __init__(self, name, bases, ns, **kwds):
print('Meta.init', self)
def __new__(self, name='Test', bases=(Test,), ns={}, **kwds):
print('Meta.new', self, name, bases, ns, kwds)
return type(name, (self,), dict(ns))
class Test(metaclass=Meta):
def __init__(self):
print('Test.init', self)
def __new__(self, *args, **kwds):
print('Test.new', self)
return super().__new__(self)
t = Test()
print('='*20)