关于__new__和__init__

2022-10-20,

关于__new____init__

例如一个类

class foo(object):
    def __init__(self):
        print(1)
        
    def __new__(self):
        print(2)
#2
  • new会优先int执行
  • 其实就相当于子类的里面的new方法覆盖的obj里面的new方法当子类里面没有返回值的时候,将不执行init方法
class foo(object):
    def __init__(self):
        print(self)
        print(1)

    def __new__(self):
        print(2)
        return 2
  • 当返回值不是object类时候也不会执行int方法
class foo(object):
    def __init__(self):
        print(self)
        print(1)

    def __new__(cls):
        print(2)
        return object.__new__(cls)
'''
2
<__main__.foo object at 0x000000000213c278>
1
'''
  • 当返回值是个object类时候,会执行int方法且int里面的self就是new返回的类

当我们想要一个具有参数的的新类的时候

class demo(object):
    def __init__(self,name):
        self.name = name

    def __new__(cls, *args, **kwargs):

        return object.__new__(cls)

《关于__new__和__init__.doc》

下载本文的Word格式文档,以方便收藏与打印。