理解Python中的__init__和__new__

先来看一段代码:

class A(object):  # -> don't forget the object specified as base

    def __new__(cls):
        print ("A. __new__ called")
        return super().__new__(cls)

    def __init__(self):
        print ("A. __init__ called")

A()

输出结果:

A. __new__ called
A. __init__ called
  1. 执行的顺序是先__new____init__。因为函数__new__在我们调用类的时候会被自动调用,并且返回 instance__init__,也就是__init__中的 self

再来看一段代码:

class A(object):

    def __new__(cls):
        print ("A.__new__ called")

    def __init__(self):
        print ("A.__init__ called")  # -> is actually never called

print (A())

输出结果:

A.__new__ called
None

这里__init__并没有被调用。这是因为与之前不同,这次__new__ override 了父类的__new__之后,没有使用super()继承父类其他创建 instancemethod ,只是单纯的执行打印。所以并没有返回一个 instance__init__self。所以返回None

再来看如果在__new__中加入return功能会如何:

class A(object):
    def __new__(cls):
        print ("A. __new__ was called")
        return 29

print (A())

输出结果是:

A.__new__ called
29

得用__new__函数,我们可以在创建类的 instance 的时候返回其他类型的 instance

class Sample(object):

    def __str__(self):
        return "A returned an instance of Sample()"

class A(object):

    def __new__(cls):
        return Sample()

print (A())

输出结果:

A returned an instance of Sample()
posted @ 2017-06-24 10:27  2021年的顺遂平安君  阅读(162)  评论(0编辑  收藏  举报