python - 即使在类属性中满足要求时也会引发 AssertionError?
问题描述
我有一个类 Interval ,其类属性compare_mode
设置为None
. compare_mode 用于关系运算符,根据不同的“模式”比较值。
什么时候compare_mode
is'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:
解决方案
将您的条件更改为
Interval.compare_mode != 'liberal' and Interval.compare_mode != 'conservative'
推荐阅读
- php - Wordpress 管理员删除了数据库中未删除的用户详细信息。如何从数据库中删除 WordPress 用户
- php - 上传图片未保存在服务器 Laravel 5.8 上的目录中
- cakephp - 在没有主键的情况下向表中插入新记录(CakePHP)
- java - 使用 JAVA 通过 SFTP 将文件从服务器传输到另一个服务器
- angular - 当鼠标移过 FullCalendar 中的元素时如何放置事件?
- php - WordPress 元查询
- java - jenkins 中的传递依赖管理
- database - 一致性 LocalQuorum 读取查询期间的 Cassandra 超时
- jenkins-pipeline - XLDeploy 部署失败时如何禁用回滚
- javascript - 根据名称将序列化的 JS 数组分组为相似的数组