Python 小知识点(8)-- __new__

第一段代码如下:

class Foo(object):

    def __init__(self,name):
        self.name = name

        print("Foo __init__")

    def __new__(cls, *args, **kwargs):
        print("Foo __new__")
        return object.__new__(cls)
f = Foo("Td")
输出结果为:
Foo __new__
Foo __init__

当把return object.__new__(cls)注释了后:

代码如下:

class Foo(object):

    def __init__(self,name):
        self.name = name


    def __new__(cls, *args, **kwargs):
        print("Foo __new__")
        #return object.__new__(cls) # cls此时表示Foo
  f = Foo("Td") 结果为:Foo __new__

结论:

对比上述两种结果:可以得出__new__是用来实例化,在__new__中调用了__init__,简而言之,在实例化是是__new__触发了__init__方法。(默认就有)

return object.__new__(cls)的作用:继承父类的__new__方法。

(1)   object.__new__(cls):继承父类的写法,

(2)   cls表示子类(当前类对象)

 源码学习地址:https://gitee.com/FelixBinCloud/PythonLearn/commit/384f0d77502ec9d02c66fcb9b7ba1672619885a1

原文地址:https://www.cnblogs.com/wfaceboss/p/9449905.html