我想覆盖__cmp__
、__eq__
和__hash__
方法,以便在SQLAlchemy Declarative Base模型上执行集合操作。这样做会与Declarative Base实现产生任何冲突吗?
我想覆盖__cmp__
、__eq__
和__hash__
方法,以便在SQLAlchemy Declarative Base模型上执行集合操作。这样做会与Declarative Base实现产生任何冲突吗?
也许会根据比较函数的实现而定。
当使用__eq__
或__cmp__
与other
对象进行比较时,必须小心,因为SQLAlchemy可能会将您的对象与某些符号(例如NEVER_SET
)进行比较,这些符号与您的对象类型不同。请查看此SQLAlchemy方法:
def get_all_pending(self, state, dict_):
if self.key in dict_:
current = dict_[self.key]
if current is not None:
ret = [(instance_state(current), current)]
else:
ret = [(None, None)]
if self.key in state.committed_state:
original = state.committed_state[self.key]
if original not in (NEVER_SET, PASSIVE_NO_RESULT, None) and \
original is not current:
ret.append((instance_state(original), original))
return ret
else:
return []
原始不在(NEVER_SET,PASSIVE_NO_RESULT,None)这行代码可能会引发错误,如果比较没有首先检查类型的相等性或比较中使用的字段的存在性。
解决方法是考虑不同类型。此外,请避免覆盖 __cmp__ 并改用富比较运算符。
不会出问题,它能正常工作。