【问题标题】:How to override equals() in google app engine data model type?如何在谷歌应用引擎数据模型类型中覆盖 equals()?
【发布时间】:2011-03-05 16:40:10
【问题描述】:

我正在为 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”字段?

提前致谢

【问题讨论】:

    标签: python google-app-engine web-applications


    【解决方案1】:

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

    【讨论】:

    • 您不需要重写 ne - 默认实现 IIRC 调用 eq。另外,从调用内置方法返回异常类?怎么回事?举起它!
    • @Nick Johnson,对不起,但你在这两种情况下都错了,NotImplemented 也不例外,阅读docs.python.org/library/constants.html#NotImplemented 并尝试删除__ne__print UserAccount() == UserAccount(), UserAccount() != UserAccount() 打印True True :)
    • @Nick Johnson,stackoverflow.com/questions/878943/… 解释了为什么 NotImplemented 而不是 NotImplementedError
    • 道歉。你在这两个方面都完全正确,我错了。至少我学到了一些新东西! :)
    • 谢谢你们,你们帮了大忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多