iT邦幫忙

DAY 26
0

Python初學起步走系列 第 26

[Python初學起步走-Day26] - 物件導向(Object-oriented,OO) - 特殊方法(比較)

延續使用昨天與前天的人類(Human)物件

#myclass.py
class Human:
    def __init__(self,h=0,w=0):
        self.height=h
        self.weight=w
    def BMI(self):
        return self.weight / ((self.height/100)**2)

我們若想定義人類(Human)物件要怎麼比較

例如

import myclass
a = myclass.Human(180,80)
b = myclass.Human(170,70)
a>b????
a!=b????

我們可以實作覆寫掉對應的特殊方法

__lt__ 小於(<)
__le__ 小於等於(<=)
__eq__ 等於(==)
__ne__ 不等於(!=)
__gt__ 大於(>)
__ge__ 大於等於(>=)

舉個例子

我們設定如果a人類(Human)物件的BMI值 > b人類(Human)物件的BMI就傳回True否則False

#myclass.py
class Human:
    def __init__(self,h=0,w=0):
        self.height=h
        self.weight=w
    def BMI(self):
        return self.weight / ((self.height/100)**2)
    def __gt__(self,other):
        return float(self.BMI()) > float(other.BMI())






#main.py
import myclass
a = myclass.Human(180,80)
print("a.BMI()",a.BMI())
b = myclass.Human(170,70)
print("b.BMI()",b.BMI())
print(a>b)
print(b>a)


上一篇
[Python初學起步走-Day25] - 物件導向(Object-oriented,OO) - 繼承
下一篇
[Python初學起步走-Day27] - 物件導向(Object-oriented,OO) - 特殊方法(運算子)
系列文
Python初學起步走30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
alan_lee
iT邦新手 5 級 ‧ 2018-06-24 13:41:45

您好, 如果已經寫了print(a>b) 或著 print(b>a), 那為什麼還需要在Human裏頭使用_gt_呢?

我要留言

立即登入留言