两个类的实例相互加减 重写类的运算 __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>

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