# `__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
```