小甲魚 入門學習python筆記 魔法方法

2022-07-15 21:57:14 字數 1146 閱讀 5406

//

__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)

//

反運算//

左運算元不支援相應的操作時右運算元的反運算方法會被呼叫。

>>> class newint(int

): def __add__(self,other):

print(

"add 被呼叫")

def __radd__(other,self):

print(

"radd 被呼叫")

>>> a = newint(5

)>>> b= newint(6

)>>> a +b

add 被呼叫

>>> 1+a

radd 被呼叫

學習小甲魚Python入門(二)習題筆記 列表

a a b c a.竹林小溪 crazy迷戀 竹林小溪 crazy迷戀 作為乙個元素 a b c 竹林小溪 crazy迷戀 a a b c a.extend 竹林小溪 crazy迷戀 竹林小溪 crazy迷戀 兩個元素,打包一起 a a b c 竹林小溪 crazy迷戀 假設給定以下列表 membe...

小甲魚python零基礎入門 學習筆記 元組

簡單來說 元組就是不能修改值的列表,即不可變的列表。如果需要儲存的一組值在程式的整個生命週期內不變,可使用元組。元組與列表在 上的區別 元組的定義用 型別是tuple 列表的定義用,型別是list name list peter william jack tom alice jim type nam...

python學習筆記2 小甲魚課程

1.idle是python的外殼 2.idle file new file 輸入程式段 3.快捷鍵 alt n 上一條語句 f5 執行程式段 4.dir builtins 檢視所有內建函式 5.help 檢視具體的某個函式怎麼用,例如 help input 6.python不允許if條件中賦值,例如...