zoukankan      html  css  js  c++  java
  • 【python】__new__和__init__区别

    原文:http://blog.csdn.net/cnmilan/article/details/8849680
    __new__:创建对象时调用,返回当前对象的一个实例
    __init__:创建完对象后调用,对当前对象的实例的一些初始化,无返回值


    测试1:
    >>> class A(object):
    def __init__(self):
    print("in init")
    def __new__(self):
    print("in new")

    >>> A()
    in new


    测试2:
    class A(object):
    def __new__(Class):
    Object = super(A, Class).__new__(Class)
    print "in New"
    return Object
    def __init__(self):
    print "in init"

    class B(A):
    def __init__(self):
    print "in B's init"

    B()
    >>>
    in New
    in B's init

    对于New来说:
    Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance ofcls).

    Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

    这也是上面的例子2

    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__().

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

    __new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

    object.__init__(self[, ...])
    Called when the instance is created. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self, [args...]). As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.  
  • 相关阅读:
    Java 集合系列06之 Vector详细介绍(源码解析)和使用示例
    Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例
    Java 集合系列02之 Collection架构
    Java 集合系列01之 总体框架
    [转载] 散列表(Hash Table) 从理论到实用(下)
    [转载] 散列表(Hash Table)从理论到实用(中)
    [转载] 散列表(Hash Table)从理论到实用(上)
    Android 之窗口小部件高级篇--App Widget 之 RemoteViews
    Android控件之GridView
    红黑树(一)之 原理和算法详细介绍
  • 原文地址:https://www.cnblogs.com/itaceo-o/p/3300289.html
Copyright © 2011-2022 走看看