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)