類支援比較操作

2021-09-08 16:29:00 字數 2257 閱讀 2626

讓某個類的例項支援標準的比較運算(比如》=,!=,<=,《等),但是又不想去實現那一大丟的特殊方法。

python類對每個比較操作都需要實現乙個特殊方法來支援。 例如為了支援》=操作符,你需要定義乙個 、_ge_() 方法。 儘管定義乙個方法沒什麼問題。

裝飾器 functools.total_ordering 就是用來簡化這個處理的。 使用它來裝飾乙個來,你只需定義乙個 _eq_() 方法, 外加其他方法(_lt_, _le_, _gt_, or _ge_)中的乙個即可。 然後裝飾器會自動為你填充其它比較方法。

例如:

from functools import total_ordering

class room(object):

def __init__(self, name, length, width):

self.name = name

self.length = length

self.width = width

self.square_feet = self.length * self.width

@total_ordering

class house(object):

def __init__(self, name, style):

self.name = name

self.style = style

self.rooms = list()

@property

def living_space_footage(self):

return sum(r.square_feet for r in self.rooms)

def add_room(self, room):

def __str__(self):

return '{}: {} square foot {}'.format(self.name,

self.living_space_footage,

self.style)

def __eq__(self, other):

return self.living_space_footage == other.living_space_footage

def __lt__(self, other):

return self.living_space_footage < other.living_space_footage

if __name__ == "__main__":

h1 = house('h1', 'cape')

h1.add_room(room('master bedroom', 14, 21))

h1.add_room(room('living room', 18, 20))

h1.add_room(room('kitchen', 12, 16))

h1.add_room(room('office', 12, 12))

h2 = house('h2', 'ranch')

h2.add_room(room('master bedroom', 14, 21))

h2.add_room(room('living room', 18, 20))

h2.add_room(room('kitchen', 12, 16))

h3 = house('h3', 'split')

h3.add_room(room('master bedroom', 14, 21))

h3.add_room(room('living room', 18, 20))

h3.add_room(room('office', 12, 16))

h3.add_room(room('kitchen', 15, 17))

houses = [h1, h2, h3]

print('is h1 bigger than h2?', h1 > h2) # prints true

print('is h2 smaller than h3?', h2 < h3) # prints true

print('is h2 greater than or equal to h1?', h2 >= h1) # prints false

print('which one is biggest?', max(houses)) # prints 'h3: 1101-square-foot split'

print('which is smallest?', min(houses)) # prints 'h2: 846-square-foot ranch'

讓類支援比較操作

有時我們希望自定義類,例項間可以使用 號進行比較,我們自定義比較行為。例如,有乙個矩形類,我們希望比較兩個矩形的例項時,比較的是面積。class rectangle def init self,w,h self.w w self.h h defarea self return self.w self...

python如何讓類支援比較運算

案例 有時我們希望自定義的類,例項間可以使用比較運算子進行比較,我們自定義比較的行為。需求 有乙個矩形的類,我們希望比較兩個矩形的例項時,比較的是他們的面積 如何解決這個問題?在類中重新定義比較運算子,所有的比較運算可以簡化為兩個基本的比較運算,小於和等於比較 單個模擬較 usr bin pytho...

MFC對檔案操作的支援 CFile 類

cfile類提供了沒有快取的二進位制格式的磁碟檔案輸入輸出功能。建構函式 cfile lpctstr lpszfilename,uint nopenflags lpszfilename 檔名 nopenflags 檔案訪問和共享的方式 經典取值 cfile modecreate cfile mode...