关于__new__和__init__

关于__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)

posted @ 2019-07-22 20:57  小小咸鱼YwY  阅读(369)  评论(0编辑  收藏  举报