python类运算符重载——重写print和sort

\quad python提供了很多内建函数,可以供我们自定义加减乘除、打印、迭代等方法。这里我给出最常见的两个方法:

  • 重写__str__以完成打印输出
  • 重写__lt__,即<符号以实现在外部可直接调用sorted函数按照我们自定义的排序符号进行排序

\quad 下面给出示例:

class Event(object):
    def __init__(self, time, location, describe):
        self.time = time
        self.location = location
        self.describe = describe
    # 重写print
    def __str__(self):
        return ("time: {}; location: {}; describe: {}".format(self.time, self.location, self.describe))
    # 重写 < 符号用于sorted
    def __lt__(self, other):
        return self.time < other.time
    

if __name__ == '__main__':
    event1 = Event(time="2019-11-13", location="California", describe="Wildfire in CA.")
    event2 = Event(time="2020-01-12", location="NY", describe="xxx")
    event3 = Event(time="2016-12-13", location="UK", describe="xxx")

    events = [event1, event2, event3]
    # 按照类的time属性从小到大排序输出
    events = sorted(events)
    for event in events:
        print(event)

python类运算符重载——重写print和sort_第1张图片

你可能感兴趣的:(python学习)