自定义Python类中的单函数比较

时间:2019-09-23 12:51:51

标签: python python-3.x oop comparison

由于各种原因(排序,设置用法等),我经常需要使我的类具有可比性,并且我不想每次都编写多个比较函数。我如何支持该类,所以我只需要为每个新类编写一个函数?

1 个答案:

答案 0 :(得分:1)

我对这个问题的解决方案是创建一个抽象类,该类可以使用所需的比较方法继承并覆盖主比较函数(diff())。

class Comparable:
    '''
    An abstract class that can be inherited to make a class comparable and sortable.
    For proper functionality, function diff must be overridden.
    '''
    def diff(self, other):
        """
        Calculates the difference in value between two objects and returns a number.
        If the returned number is
        - positive, the value of object a is greater than that of object b.
        - 0, objects are equivalent in value.
        - negative, value of object a is lesser than that of object b.
        Used in comparison operations.
        Override this function."""
        return 0

    def __eq__(self, other):
        return self.diff(other) == 0

    def __ne__(self, other):
        return self.diff(other) != 0

    def __lt__(self, other):
        return self.diff(other) < 0

    def __le__(self, other):
        return self.diff(other) <= 0

    def __gt__(self, other):
        return self.diff(other) > 0

    def __ge__(self, other):
        return self.diff(other) >= 0
相关问题