• 技术文章 >Python技术 >Python基础教程

    python如何在自定义类上使用堆排序

    小妮浅浅小妮浅浅2021-05-14 09:38:26原创2823

    1、说明

    我们留给自定义类的唯一解决方案是实际重写比较运算符。遗憾的是,这使我们局限于对每个类只能进行一种比较。在我们的示例中,我们被局限于按年份对Movie对象进行排序。

    但是,它确实让我们演示了在自定义类上使用堆排序。我们来定义Movie类:

    2、实例

    from heapq import heappop, heappush
     
    class Movie:
        def __init__(self, title, year):
            self.title = title
            self.year = year
     
        def __str__(self):
            return str.format("Title: {}, Year: {}", self.title, self.year)
     
        def __lt__(self, other):
            return self.year < other.year
     
        def __gt__(self, other):
            return other.__lt__(self)
     
        def __eq__(self, other):
            return self.year == other.year
     
        def __ne__(self, other):
            return not self.__eq__(other)

    以上就是python在自定义类上使用堆排序的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python 堆排序
    品易云
    上一篇:python中super的使用注意 下一篇:python中的mro是什么?

    相关文章推荐

    • python进程的交流方式• python中Queue和pipe的差别• python中re有哪些常用函数• python堆排序是什么?• python创建和使用堆的方法• python中super的使用注意

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网