zoukankan      html  css  js  c++  java
  • Python_中__init__和__new__的异同

    1:__new__:它是创建对象时调用,会返回当前对象的一个实例;

         __init__:它是创建对象后调用,对当前对象的一些实例初始化,无返回值

    代码示例:

    >>> class Data(object):
        def __init__(cls):
            cls.x = 2
            print "init"
            return cls    ###在init中不可用
    
        
    >>> data = Data()
    init
    
    Traceback (most recent call last):
      File "<pyshell#100>", line 1, in <module>
        data = Data()
    TypeError: __init__() should return None, not 'Data'
    
    >>> class Data(object):
        def __new__(cls):
            cls.x = 3
            print "new"
            return cls
    
        
    >>> data = Data()
    new
    >>> data.x
    3

    由上可见,__new__方法会返回所构造的对象,__init__则不会,__init__无返回值

    2:再类中,若__new__和__init__同时存在时,先调用__new__

    代码示例:

    >>> class Data(object):
        def __new__(self):
            print "new"
        def __init__(self):
            print "init"
    
            
    >>> data = Data()
    new

    3:If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

    如果__new__返回一个对象的实例,会隐式调用__init__

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

    如果__new__不返回一个对象的实例,__init__不会被调用

    代码示例:

    >>> class A(object):
        def __new__(Class):
            object = super(A,Class).__new__(Class)
            print "in new"
            return object   ##返回对象的实例
        def __init__(self):
            print "in init"
    
            
    >>> A()
    in new
    in init
    <__main__.A object at 0x0215CD70>
    >>> class B(object):
        def __new__(cls):
            print "in new"
            return cls
        def __init__(self):
            print "in init"
    
            
    >>> b=B()
    in new
    每天多一点提高,给自己一些激励,开心生活,用编码来丰富我的生活,加油! ↖(^ω^)↗
  • 相关阅读:
    差分序列
    蓝桥杯 操作格子
    线段树
    历届题目 密文搜索
    对局匹配(动态规划)
    历届试题 分巧克力(二分查找)
    第九届蓝桥杯B组决赛 调手表(完全背包)
    快速幂求余
    2019蓝桥杯国赛备赛题库
    ubuntu16.04安装cuda8.0试错锦集
  • 原文地址:https://www.cnblogs.com/graceting/p/3621131.html
Copyright © 2011-2022 走看看