Python中的數據模型

Python中的數據模型

__new__ 與 __init__ 的區別

  • __new__在__init__之前調用
  • __new__在返回一個類的實例時,會調用類的__init__函數
  • __new__沒有返回類的實例,或者返回的實例對應的類沒有__init__,則不會調用__init__

  1. type與object作爲父類的區別
  2. 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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章