1. 程式人生 > >[小甲魚]入門學習python筆記 【魔法方法】

[小甲魚]入門學習python筆記 【魔法方法】

實例化 魔法 sel width 對象 重寫 pre body wid

//__new__(cls[,....])
//對象實例化調用的第一個方法,它的第一個參數是這個類,而其他參數會直接傳遞給__init__()方法
//需要在基類的基礎上對其進行修改時重寫__new__()方法

技術分享圖片

//__del__()方法
//只有在該類實例化的對象全部被del掉時,才調用__del__()方法

技術分享圖片

//python 中的運算符重載

class New_int(int):   //基於基類int的子類New_int
    def__add__(self,other)    //重載運算符 +
        return int.__sub__(self,other)   //返回基類的減法運算

class
New_Int(int): def__add__(self,other): return int(self)-int(other) // 等價於int. __sub__(self,other) >>>a = New_Int(1) >>>b = New_int(3

[小甲魚]入門學習python筆記 【魔法方法】