【发布时间】:2015-06-10 00:23:16
【问题描述】:
通过abstract base classes,Python 提供了一种无需实际尝试即可了解对象行为的方法。在标准库中,我们在collections.abc 中为容器定义了一些 ABC。例如,可以测试一个参数是否可迭代:
from collections.abc import Iterable
def function(argument):
if not isinstance(argument, Iterable):
raise TypeError('argument must be iterable.')
# do stuff with the argument
我希望有一个这样的 ABC 来决定是否可以比较一个类的实例,但找不到。测试 __lt__ 方法的存在是不够的。例如,无法比较字典,但仍定义了 __lt__(实际上与 object 相同)。
>>> d1, d2 = {}, {}
>>> d1 < d2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()
>>> hasattr(d1, '__lt__')
True
所以我的问题是:有没有一种简单的方法可以做到这一点,而无需自己进行比较并捕捉TypeError?
我的用例类似于排序容器:我想在插入第一个元素时引发异常,而不是等待第二个元素。我考虑过将元素与自身进行比较,但有没有更好的方法:
def insert(self, element):
try:
element < element
except TypeError as e:
raise TypeError('element must be comparable.')
# do stuff
【问题讨论】:
标签: python python-3.x comparison-operators abstract-base-class