zoukankan      html  css  js  c++  java
  • python __new__ 与__init__函数

    __new__(cls[, ...])

    This method is only used for new-style classes (classes inheriting from object).

    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 of cls).

    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.

    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.

    __new__主要可以用来继承。

    class A(object):
      def __new__(cls, *args, **kwds):
        print "one"
        print "A.__new__", args, kwds
        return object.__new__(B, *args, **kwds)
      def __init__(cls, *args, **kwds):
        print "two"
        print "A.__init__", args, kwds
    class B(object):
      def __new__(cls, *args, **kwds):
        print "three"
        print cls
        print B
        print "B.__new__", args, kwds
        return object.__new__(cls, *args, **kwds)
      def __init__(cls, *args, **kwds):
        print "four"
        print "B.__init__", args, kwds
    class C(object):
      def __init__(cls, *args, **kwds):
        print "five"
        print "C.__init__", args, kwds
    print C()
    print "====================="
    print A()
    print "====================="
    print B()

    And here's the result of running that code:

    40:~/ndfi grahamellis$ python newvinit
    five
    C.__init__ () {}
    <__main__.C object at 0x6fc10>
    =====================
    one
    A.__new__ () {}
    <__main__.B object at 0x6fc10>
    =====================
    three
    <class '__main__.B'>
    <class '__main__.B'>
    B.__new__ () {}
    four
    B.__init__ () {}
    <__main__.B object at 0x6fc10>
    40:~/ndfi grahamellis$


  • 相关阅读:
    计算几何——交点、面积的计算
    计算几何——认识基本object:点、线、面 。
    图的拓扑排序——卡恩算法
    Manacher
    如何不改造 HBase 就能应对复杂查询场景
    如何做沟通
    大数据磁盘阵列技术
    Android系统架构开篇
    Apache Kylin 原理介绍与新架构分享(Kylin On Parquet)
    遭遇突然提问慌了?掌握关键2点完美应对zz
  • 原文地址:https://www.cnblogs.com/lovemo1314/p/2034927.html
Copyright © 2011-2022 走看看