【问题标题】:AssertionError raised even when requirements are met in a class attribute?即使在类属性中满足要求时也会引发 AssertionError?
【发布时间】:2021-10-27 03:38:55
【问题描述】:

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

compare_mode'liberal''conservative' 时,它应该转到__lt__ 中各自的if-else 语句并进行比较,但即使我已将compare_mode 设置为'liberal' 或@ 987654329@,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:

【问题讨论】:

    标签: python class operator-overloading


    【解决方案1】:

    改变你的条件

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

    【讨论】:

    • 啊。如此简单的错误,我不敢相信我忽略了它。回想起来是有道理的。谢谢你的帮助
    猜你喜欢
    • 2021-11-18
    • 2021-04-21
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多