擅长:python、mysql、java
<p>我会这样做:</p>
<pre><code>class D1(object):
def __val_cmp(self, other):
# compare by attributes here
if self.attr < other.attr:
return -1
elif self.attr > other.attr:
return 1
return 0
def __cmp__(self, other):
greater = isinstance(other, type(self))
lesser = isinstance(self, type(other))
if greater and lesser:
# same type so compare by attributes
return self.__val_cmp(other)
elif greater:
return 1
elif lesser:
return -1
else:
# other type is not a parent or child type, so just compare by attributes
return self.__val_cmp(other)
</code></pre>
<ul>
<li>如果D2是D1的子类型,则D2的实例将始终比D1的实例少。在</li>
<li>如果D0是D1的父类型,则D0实例的比较将始终大于D1的实例。在</li>
<li>如果将D1的一个实例与D1的另一个实例进行比较,则将根据类的属性进行比较。在</li>
<li>如果将D1的实例与未知类的实例进行比较,则将按类的属性进行比较</li>
</ul>