total_ordering
total_ordering
:允许类只定义__eq__
和其他中的一个,其他
富比较方法由装饰器自动填充
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| from functools import total_ordering
class Room: 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: 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): self.rooms.append(room)
def __str__(str): return "{}: {} squre 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
|