如何在谷歌应用引擎数据模型中重写equals()?
我正在使用Python的Google App Engine库。我想知道如何在一个类中重写equals()
方法,使它只根据user_id
字段来判断两个对象是否相等。
class UserAccount(db.Model):
# compare all equality tests on user_id
user = db.UserProperty(required=True)
user_id = db.StringProperty(required=True)
first_name = db.StringProperty()
last_name = db.StringProperty()
notifications = db.ListProperty(db.Key)
现在,我是通过获取一个UserAccount
对象,然后比较user1.user_id == user2.user_id
来判断是否相等的。有没有办法让我重写这个方法,让'user1 == user2'只关注'user_id'字段呢?
提前谢谢你!
1 个回答
14
重写运算符 __eq__
(==) 和 __ne__
(!=)
例如:
class UserAccount(db.Model):
def __eq__(self, other):
if isinstance(other, UserAccount):
return self.user_id == other.user_id
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result