使一个类具有可比性,以便我可以获得列表中类实例的最大参数值(Python)
我有一个定义单个元素 (Request
) 的类和另一个由 Request
实例组成的类 (RequestsBook
)。 RequestsBook
还具有将更多请求附加到书中的方法。
class Request:
def __init__(self, req_id, req_type, value):
self.req_id = req_id
self.req_type= req_type
self.value = value
class RequestsBook:
def __init__(self):
self.requests_book = list()
def add(self, new_req):
self.requests_book.append(new_req)
def get_max_value_of_type(self, req_type):
# pass
如上所示,我想了解如何有效地获取 RequestsBook
列表中匹配的那些 Request
实例的最大值
特定类型。
例如:
rb = RequestsBook()
rb.add(Request(1, 'A', 100))
rb.add(Request(2, 'B', 42))
rb.add(Request(3, 'A', 78))
rb.add(Request(4, 'A', 12))
rb.get_max_value_of_type('A') # should return 190
rb.get_max_value_of_type('B') # should return 42
根据我的理解,我需要使用 functools.total_ordering 装饰器。
我以前从未使用过这个装饰器,并且正在努力想出一种有效的方法来实现 get_max_value_of_type 。遗憾的是,该用例的在线示例并不多。任何帮助将不胜感激。
I have a class that defines a single element (Request
) and another class (RequestsBook
) that is comprised from Request
instances. The RequestsBook
also has methods to append more requests into the book.
class Request:
def __init__(self, req_id, req_type, value):
self.req_id = req_id
self.req_type= req_type
self.value = value
class RequestsBook:
def __init__(self):
self.requests_book = list()
def add(self, new_req):
self.requests_book.append(new_req)
def get_max_value_of_type(self, req_type):
# pass
As seen above, I want to understand how I can efficiently get the maximum value
of those Request
instances inside the RequestsBook
list that match a specific type.
For example:
rb = RequestsBook()
rb.add(Request(1, 'A', 100))
rb.add(Request(2, 'B', 42))
rb.add(Request(3, 'A', 78))
rb.add(Request(4, 'A', 12))
rb.get_max_value_of_type('A') # should return 190
rb.get_max_value_of_type('B') # should return 42
Based on my understanding, I need to make the Request
class comparable using the functools.total_ordering decorator.
I have never used this decorator before and I am struggling to think of an efficient way to implement get_max_value_of_type
. Sadly, there are not many online examples for this use case. Any help will be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码按类型排序,然后按值排序,然后检索最大值作为最后一项。它使用
sorted
内置函数以及来自operator
模块的attrgetter
关键函数。它遵循 Python 文档 (3.10) 中的排序 HOWTO 教程中的说明。This code sorts by type then sorts by value then retrieves the maximum as the last item. It uses
sorted
builtin with a key function,attrgetter
from theoperator
module. It follows the explanation in the Sorting HOWTO tutorial in Python docs (3.10).