代码之家  ›  专栏  ›  技术社区  ›  Cuga

如何重写google app engine数据模型类型中的equals()?

  •  11
  • Cuga  · 技术社区  · 15 年前

    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\u id”字段?

    提前谢谢

    1 回复  |  直到 15 年前
        1
  •  14
  •   Anurag Uniyal    15 年前

    重写运算符 __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