企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# `__NEW__` 函数说明 ## 1. 功能说明 _说明_:`__new__` 先说明`__init__` 实例化的对象,一般是说的是`__init__`执行初始化,其实`__init__` 并不是第一个被调用的内置函数.其实最先被调用的方法是`__new__`的方法.那么我们并没有写,那调用的是谁呢? ## 演示代码 ```python class Person: def __init__(self): print("do init") # 在执行完new之后才调用init def __new__(cls, *args, **kwargs): print("do new") # 首先调用内置函数new开启对象空间 return super(Person,cls).__new__(cls) # 这是第一种方式 if __name__ == '__main__': s1 = Person() print(s1) """ 结果 do new do init <__main__.Person object at 0x7ff766cd86d8> """ ``` ## 单例模式演示 ### 代码 ```python class Singleton: def __new__(cls, *args, **kwargs): if not hasattr(cls,'instance'): cls.instance = super(Singleton,cls).__new__(cls) return cls.instance obj1 = Singleton() obj2 = Singleton() obj1.instance = 'value1' obj2.instance = 'value2' print(obj1.instance,obj2.instance) # value2 value2 print(obj1 is obj2) # True print(obj1 == obj2) # True print(id(obj1) == id(obj2)) # True ```