兩個類的實例相互加減 重寫類的運算 __add__ __sub__ 方法

class MyClass:
    def __init__(self, long, weight):       #類定義2個屬性
        self.long = long
        self.weight = weight
    def __str__(self):                      #字符串輸出
        return 'MyClass (%d, %d)' % (self.long, self.weight)
    def __add__(self, other):
        return MyClass(self.long + other.long, self.weight + other.weight)   #通過類返回
    def __sub__(self,other):
        return MyClass(self.long-other.long,self.weight-other.weight)   #通過類返回
    def intro(self):      #類的輸出方法
        print("長爲",self.long,"寬爲",self.weight)
        
>>>a=MyClass(10,20)   #類的實例化
>>>a.intro()       #調用類的方法
長爲 10 寬爲 20
>>>b=MyClass(30,50)     #類的實例化
>>>b.intro()     #調用類的方法
長爲 30 寬爲 50

>>>c=b-a          #調用__sub__方法
>>>c.intro()
長爲 20 寬爲 30
>>>print(a)       #使用__str__方法
MyClass (10, 20)
>>>a
<MyClass object at 0x044A3910>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章