今天來看加減乘除法的部分,加法呢還是沿用我們的bmiclass
#bmiclass.py
class health:
def __init__(self,h=0,w=0):
self.height=h
self.weight=w
def BMI(self):
return self.weight / ((self.height/100)**2)
實作覆寫掉對應的特殊方法!
__add__ +
__sub__ -
__mul__ *
__truediv__ /
依樣我們舉例子
把a同學和b同學的bmi互相加減乘除
def __add__(self,other):
return float(self.BMI()) + float(other.BMI())
def __sub__(self,other):
return float(self.BMI()) - float(other.BMI())
def __mul__(self,other):
return float(self.BMI()) * float(other.BMI())
def __truediv__(self,other):
return float(self.BMI()) / float(other.BMI())