__new__和__init__

__new__是用来创造一个类的实例的(constructor)

__init__是用来初始化一个实例的(initializer)。

class newStyleClass(object):

    def __new__(cls):
        print("__new__ is called")
        return super(newStyleClass, cls).__new__(cls)

    def __init__(self):
        print("__init__ is called")
        print("self is: ", self)

newStyleClass()
'''
__new__ is called
__init__ is called
self is:  <__main__.newStyleClass object at 0x000001307DDEB488>
'''

(2)如果__new__函数返回一个已经存在的实例(不论是哪个类的),__init__不会被调用。

obj = 12
class returnExistedObj(object):
    def __new__(cls):
        print("__new__ is called")
        return obj

    def __init(self):
        print("__init__ is called")

returnExistedObj()
'''
__new__ is called
'''

(3)在__new__函数中不返回任何对象,则__init__函数也不会被调用。

class notReturnObj(object):
    def __new__(cls):
        print("__new__ is called")

    def __init__(self):
        print("__init__ is called")

print(notReturnObj())
'''
__new__ is called
None
'''

(4)__new__返回一个新创建不属于该类的实例时,当前类的__init__不会被调用。

class sample(object):
    def __str__(self):
        print("sample")

class example(object):
    def __new__(cls):
        print("__new__ is called")
        return sample()

    def __init__(self):
        print("__init__ is called")

example()
'''
__new__ is called
'''

 

posted on 2020-11-18 14:59  happygril3  阅读(86)  评论(0)    收藏  举报

导航