__new()__与__init__()

1. __new__:创建对象时调用,会返回当前对象的一个实例。(默认情况下也就是你在类中没有没有重新这个方法,会默认返回当前类的示例,如果你重写了这个方法,但是在方法中没有返回当前类的示例,那么也就是说没有创建对象,也就不会执行init方法)

2. __init__:创建完对象后调用,对当前对象的一些实例初始化,无返回值。(只有在__new__方法中返回当前类的示例时,才会自动执行)

3. 在类中,如果__new__和__init__同时存在,会优先调用__new__。

class NameInfo:

    def __new__(cls, *args, **kwargs):  # 创建对象的时候执行
        print('__new__')
        # return super(NameInfo, cls).__new__(cls)  # 如果注释不执行,不会执行init方法,因为没有返回类的示例,在实例化类时,也不会创建出对象

    def __init__(self, name, *args, **kwargs):  # 初始化对象的时候执行
        self.name = name
        print("__init__")

    @property
    def get_name(self):
        return self.name

    @get_name.setter
    def get_name(self,new_name):
        self.name = new_name


if __name__ == "__main__":
    alex = NameInfo('ALEy')

2. __new__()方法还可以用来实现单例模式

class NameInfo:

    def __new__(cls, *args, **kwargs):  # 创建对象的时候执行
        if not hasattr(cls, 'instance'):
            # 创建实例
            cls.instance = super(NameInfo, cls).__new__(cls)
            # print(cls.instance)
        return cls.instance

    def __init__(self, name, *args, **kwargs):  # 初始化对象的时候执行
        self.name = name
        print("__init__")


if __name__ == "__main__":
    alex = NameInfo('ALEy')
    eric = NameInfo('eric')
    print(id(alex))
    print(id(eric))

C:python35python.exe D:/workspace/spider/text.py
>>>> __init__
>>>> __init__
>>>> 2947617811816
>>>> 2947617811816

参考文档:https://www.cnblogs.com/jayliu/p/9013155.html

原文地址:https://www.cnblogs.com/yuqiangli0616/p/10267403.html