python的__new__()方法

概述

学过C++/JAVA的同学都知道面向对象中有 构造方法,作用就是创建对象(实例化对象),并且初始化属性

在 Python 中, 创建对象 用__new__(cls) 实现

初始化属性用__init__(self)实现

__new__() 特点

  1. 类的 内置静态方法,不用 @staticmethod 标注
    第一个形参是 cls,表示 类本身

  2. 如果类中定义了__new__()方法,创建对象时,先调用__new__()方法

  3. 如果类中没有__new__()方法,那么会调用父类的__new__()方法

  4. 在__new__()方法中,通过父类的__new__()方法创建对象

  5. 必须要 返回对象。(否则不会调用__init__()方法,也 不会报错)

  6. 创建对象后,才调用__init__()方法。参数 self 就是__new__()方法返回的实例

例子

__new__()和__init__()执行顺序

class Phone:

    def __new__(cls):
        print("执行__new__()")
        # 通过父类的__new__()创建对象
        obj=super().__new__(cls)
        print(obj)
        return obj

    def __init__(self):
        print("执行__init__()")
        print(self)

iphone=Phone()

执行结果如下:

执行__new__()
<__main__.Phone object at 0x0000007248428C88>
执行__init__()
<__main__.Phone object at 0x0000007248428C88>

总结:

  1. 在调用Phone()时,先执行__new__(),后执行__init__()

  2. 两个方法的对象地址相同,说明是同一个对象

__new__()不返回对象

class Phone:

    def __new__(cls):
        print("执行__new__()")
        obj=super().__new__(cls)
        print(obj)
        # return obj

    def __init__(self):
        print("执行__init__()")
        print(self)

iphone=Phone()

执行结果如下:

执行__new__()
<__main__.Phone object at 0x0000007BF98D8C88>

只执行了__new__()方法

创建对象时传入参数

在创建对象时,要传入手机名字参数,如下:

iphone=Phone("iphone11")

定义类的方式如下:

class Phone:

    def __new__(cls,name):
        print("执行__new__(%s)"%name)
        return super().__new__(cls)

    def __init__(self,name):
        self.name=name
        print("执行__init__(%s)"%name)

iphone=Phone("iphone11")
print(iphone.__dict__)

执行结果如下:

执行__new__(iphone11)
执行__init__(iphone11)
{'name': 'iphone11'}

原文出处:/show_1EF4H2ziJXlN.html