如何在Google App引擎数据模型类型中覆盖equals()?

Cug*_*uga 11 python google-app-engine web-applications

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

现在,我通过获得一个UserAccount对象并做着做同样的事情user1.user_id == user2.user_id.有没有办法可以覆盖它,以便'user1 == user2'只查看'user_id'字段?

提前致谢

Anu*_*yal 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
Run Code Online (Sandbox Code Playgroud)

  • @Nick Johnson,对不起,但你错了两种情况,NotImplemented不是异常阅读http://docs.python.org/library/constants.html#NotImplemented并尝试删除`__ne__`和`print UserAccount()== UserAccount (),UserAccount()!= UserAccount()`打印`True True` :) (3认同)
  • 道歉.你完全正确,我错了.至少我学到了新东西!:) (3认同)