python魔法方法之簡單算術運算

2021-09-29 21:02:50 字數 703 閱讀 7432

class

test

(int):

#接收乙個int值

def__add__

(self , other)

:return

int.__sub__(self , other)

#對__add__方法進行改寫

def__sub__

(self , other)

:return

int.__add__(self , other)

#__sub__方法進行改寫

a = test(4)

b = test(5)

print

(a + b)

輸出結果為:-1

class

test

(int):

def__add__

(self , other)

:return self+other

def__sub__

(self , other)

:return self-other

a = test(4)

b = test(5)

print

(a + b)

若我們在這裡對__add__與__sub__方法改寫中涉及到了±運算,那麼將會進入乙個迭代過程,直到達到最高迭代次數,然後返回乙個報錯。

Python 魔法方法 算術運算2

print 並沒有傳入引數 else print 傳入了 d個引數,分別是 len args end for each in args print each,end class word str 儲存單詞的類,定義比較單詞的幾種方法 def new cls,word 注意我們必須要用到 new 方法...

Python魔法方法 基本的魔法方法

new cls 1.new 是在乙個物件例項化時候所呼叫的第乙個方法 2.他的第乙個引數是這個類,其他的引數是用來直接傳遞給 init 方法 3.new 決定是否使用該 init 方法,因為.new 可以直接呼叫其他類的構造方法,或者返回別的例項物件來作為本類的例項,如果 new 沒有返回例項物件,...

Python 基礎之魔法方法

構造方法類似於初始化方法,但是構造方法與其他普通的方法的不同之處在於,當乙個物件被建立之後,會立即呼叫構造方法。class servant object definit self self.servant saber fb servant fb.init print fb.servant class...