2010-06-19 22 views
11

我正在使用Google App Engine的Python庫。我如何可以覆蓋類equals()方法,以便其判斷在下面的類的user_id領域的平等:如何覆蓋谷歌應用程序引擎數據模型類型中的equals()?

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做equalty。有沒有一種方法可以覆蓋它,以便'user1 == user2'只會查看'user_id'字段?

預先感謝

回答

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 
+0

您不應該需要重寫__ne__ - 默認實現IIRC調用__eq__。此外,從調用內置方法返回一個異常類? WTF?提高它! – 2010-06-19 17:38:33

+3

@尼克約翰遜,對不起,但你在兩種情況下是錯誤的,NotImplemented不是例外閱讀http://docs.python.org/library/constants.html#NotImplemented並嘗試刪除'__ne__'和'打印UserAccount()== UserAccount(),UserAccount()!= UserAccount()'打印'True True' :) – 2010-06-20 06:11:18

+0

@Nick Johnson,也http://stackoverflow.com/questions/878943/why-return-notimplmented-instead-of-raising- notimplementederror解釋了爲什麼NotImplemented而不是NotImplementedError – 2010-06-20 06:21:21

相關問題