測試環境為 CentOS 8 x86_64 (虛擬機)
在 Class 裡 __new__ , __init__ 的差別.
- object.__new__(cls[, …]) – https://docs.python.org/3/reference/datamodel.html#object.__new__
建構函式, Called to create a new instance of class cls. __new__() - object.__init__(self[, …]) – https://docs.python.org/3/reference/datamodel.html#object.__init__
初始化函式, Called after the instance has been created (by __new__())
__new__() 與 __init__() 都是在建立 Instance 會去執行的 , __new__() 是在產生 Instance 前執行, __init__() 是產生 Instance 之後.
- 參考範例 – https://www.gushiciku.cn/pl/pI4S/zh-tw
[root@localhost ~]# vi new_init1.py class Test: def __new__(cls): print('__new__') return super().__new__(cls) def __init__(self): print('__init__') Test=Test()
執行結果
[root@localhost ~]# python3 new_init1.py __new__ __init__
說明:
__new__() 的返回值為新的 Instance,通過 super().__new__(cls[, …]) 來使用.return super().__new__(cls)
- 參考範例 – https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/374044/
[root@localhost ~]# vi new_init2.py class PositiveInteger(int): def __new__(cls, value): return super(PositiveInteger, cls).__new__(cls, abs(value)) i = PositiveInteger(-3) print (i)
執行結果
[root@localhost ~]# python3 new_init2.py 3
說明:
在回傳新 Instance 時就透過 abs 函數把數值轉成正數.return super(PositiveInteger, cls).__new__(cls, abs(value))
沒有解決問題,試試搜尋本站其他內容