我正在使用Google App Engine的Python库。如何覆盖类上的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'字段?
提前致谢
答案 0 :(得分:14)
覆盖运算符__eq__
(==)和__ne__
(!=)
e.g。
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