iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

自我學習python系列 第 25

物件導向4

今天來看加減乘除法的部分,加法呢還是沿用我們的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__ /

依樣我們舉例子
https://ithelp.ithome.com.tw/upload/images/20191009/20121024LVuRIWd0WS.jpg
把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())

https://ithelp.ithome.com.tw/upload/images/20191009/20121024A5fDnKq5Cd.png


上一篇
物件導向3
下一篇
物件導向5
系列文
自我學習python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言