python中的new和init

new(),init()

官方的几句描述

new() and init() work together in constructing objects (new() to create it, and init() to customize it)

If new() returns an instance of cls, then the new instance’s init() method will be invoked

If new() does not return an instance of cls, then the new instance’s init() method will not be invoked.

示例(类实例的创建,实例的创建中的__new__)
  • 类实例的创建
class AddMetaClass(type):	//type与他的子类称为元类,元类也是类实例,由type实例化而来
    def __new__(cls,name,bases,atrrs):		//元类中的__new__用来创建实例,其实就是创建Test类,元类中的__new__与类中的__new__都是用来创建实例,但是由于创建的实例的类型不同所以传入的参数也不同
        return super(AddMetaClass,cls).__new__(cls,name,bases,attrs)

    def __init__(self):
        pass

class Test(metaclass=AddMetaClass):		//类Test同时也是类实例,由元类AddMetaClass实例化而来,也就是说创建Test类的过程就是元类AddMetaClass实例化的过程
    pass
  • 实例的创建
class Foo(object):		//类Foo,同时也是类实例,由于未指定metaclass,默认由元类type实例化而来
    def __new__(cls,*args,**kwargs):	//类中的__new__用来创建实例,其实就是来创建foo对象,元类中的__new__与类中的__new__都是用来创建实例,但是由于创建的实例的类型不同所以传入的参数也不同
        return super(Foo,cls).__new__(cls,*args,**kwargs)	//__new__中 return实例,才会调用__init__初始化;如没有return则__init__不会被调用

    def __init__(self):
        pass

foo = Foo()		//foo实例由类实例Foo实例化而来
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值