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


我正在使用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'字段?

提前致谢


1994
2018-06-19 03:58


起源



答案:


覆盖运算符 __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

14
2018-06-19 04:57



你不应该覆盖 NE  - 默认实现,IIRC,调用 EQ。另外,从调用内置方法返回异常类? WTF?提高它! - Nick Johnson
@Nick Johnson,对不起,但在两种情况下你都错了,NotImplemented并不是异常读取 docs.python.org/library/constants.html#NotImplemented 并尝试删除 __ne__ 和 print UserAccount() == UserAccount(), UserAccount() != UserAccount() 版画 True True :) - Anurag Uniyal
@Nick Johnson也是 stackoverflow.com/questions/878943/... 解释了为什么NotImplemented而不是NotImplementedError - Anurag Uniyal
道歉。你完全正确,我错了。至少我学到了新东西! :) - Nick Johnson
非常感谢你们,你们一直都是一个很大的帮助。 - Cuga


答案:


覆盖运算符 __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

14
2018-06-19 04:57



你不应该覆盖 NE  - 默认实现,IIRC,调用 EQ。另外,从调用内置方法返回异常类? WTF?提高它! - Nick Johnson
@Nick Johnson,对不起,但在两种情况下你都错了,NotImplemented并不是异常读取 docs.python.org/library/constants.html#NotImplemented 并尝试删除 __ne__ 和 print UserAccount() == UserAccount(), UserAccount() != UserAccount() 版画 True True :) - Anurag Uniyal
@Nick Johnson也是 stackoverflow.com/questions/878943/... 解释了为什么NotImplemented而不是NotImplementedError - Anurag Uniyal
道歉。你完全正确,我错了。至少我学到了新东西! :) - Nick Johnson
非常感谢你们,你们一直都是一个很大的帮助。 - Cuga