首页 > 解决方案 > 即使在类属性中满足要求时也会引发 AssertionError?

问题描述

我有一个类 Interval ,其类属性compare_mode设置为None. compare_mode 用于关系运算符,根据不同的“模式”比较值。

什么时候compare_modeis'liberal''conservative'它应该去他们各自的 if-else 语句__lt__并进行比较,但是即使我设置compare_mode'liberal'or 'conservative',也会像值一样AssertionError被提升?__lt__None

我不确定这里发生了什么。任何解释将不胜感激。

class Interval:
    compare_mode = None
    def __init__(self, mini, maxi):
        self.mini = mini
        self.maxi = maxi
        
    @staticmethod
    def min_max(mini, maxi = None):
        assert isinstance(mini, (int,float)), "Minimum value must be an int or float"
        if maxi != None:
            assert isinstance(maxi, (int,float)), "Maximum value must be an int, float, or None"
        if maxi != None and mini > maxi:
            raise AssertionError('Minimum value is greater than the maximum value')
        elif maxi == None and isinstance(mini, (int, float)):
            maxi = mini
        return Interval(mini, maxi)

    def __lt__(self, other):
        if Interval.compare_mode != 'liberal' or Interval.compare_mode != 'conservative':
            raise AssertionError
        if not isinstance(other, (int, float, Interval)):
            return NotImplemented
        if Interval.compare_mode == 'liberal':
            if isinstance(other, (int,float)):
                return ((self.mini + self.maxi) / 2) < other
            else:
                return ((self.mini + self.maxi) / 2) < ((other.mini + other.maxi) / 2)
        elif Interval.compare_mode == 'conservative':
            if isinstance(other, (int,float)):
                return self.maxi < other
            else:
                return self.maxi < other.mini

if __name__ == '__main__':
    l = Interval.min_max(1.0,5.0)
    r = Interval.min_max(4.0,6.0)
    e = Interval.min_max(4.0,4.0)
    
    Interval.compare_mode = 'liberal'
    print(l<l)

>>> AssertionError:

标签: pythonclassoperator-overloading

解决方案


将您的条件更改为

Interval.compare_mode != 'liberal' and Interval.compare_mode != 'conservative'

推荐阅读