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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值