簡體   English   中英

Python AssertionError創建一個類

[英]Python AssertionError creating a class

我有一個類User和一個Theme類。 用戶類可以創建主題,可以將主題添加到主題的字典中,並且應該能夠返回主題的字典。 我是python的新手,因此遇到python邏輯/語法問題

class User:
    def __init__(self, name):
        self.themes = {}

    def createTheme(self, name, themeType, numWorkouts, themeID, timesUsed):
        newTheme = Theme(name, themeType, numWorkouts, themeID, timesUsed)
        return newTheme

和我的主題課:

class Theme:
    def __init__(self, name, themeType, numWorkouts, themeID, timesUsed):
        #themeType: 1 = genre, 2 = artist, 3 = song
        self.name = name
        self.themeType = themeType
        self.numWorkouts = numWorkouts
        self.themeID = themeID
        self.timesUsed = timesUsed

我在testUser中運行測試:

## test createTheme
    theme1 = Theme("theme", 2, 5, 1, 0)
    self.assertEqual(usr1.createTheme("theme", 2, 5, 1, 0), theme1)

但是我得到了-Traceback(最近一次調用是最近一次):文件“ /Tests/testUser.py”,第52行,在測試self.assertEqual(usr1.createTheme(“ theme”,2,5,1,0),theme1) AssertionError:!=

我不確定自己在做什么錯,有人可以幫忙嗎?

(此外,我在User中有以下方法,但是由於我的createTheme無法正常工作,因此還無法對其進行測試,但是我可以使用一些幫助來查看我的邏輯/語法中是否存在錯誤:

# returns dict
# def getThemes(self):
#     return self.themes
#
# def addTheme(self, themeID, theme):
#     if theme not in self.themes:
#         themes[themeID] = theme
#
# def removeTheme(self, _theme):
#     if _theme.timesUsed == _theme.numWorkouts:
#         del themes[_theme.themeID]

怎么了

當嘗試確定兩個對象是否相等時,例如obj1 == obj2 ,Python將執行以下操作。

  1. 它將首先嘗試調用obj1.__eq__(obj2) ,這是在obj1類中定義的方法,該方法應確定相等性的邏輯。

  2. 如果此方法不存在,或者返回NotImplemented ,那么Python將回退到調用obj2.__eq__(obj1)

  3. 如果仍然不確定,Python將返回id(obj1) == id(obj2) ,即它將告訴您兩個值是否在內存中是同一對象。

在測試中,Python必須退回到第三個選項,並且您的對象是Theme類的兩個不同實例。

你想發生什么

如果您希望對象Theme("theme", 2, 5, 1, 0) usr1.createTheme("theme", 2, 5, 1, 0) Theme("theme", 2, 5, 1, 0)usr1.createTheme("theme", 2, 5, 1, 0)相等,因為它們具有相同的屬性,則必須定義Theme.__eq__方法。

class Theme:
    def __init__(self, name, themeType, numWorkouts, themeID, timesUsed):
        #themeType: 1 = genre, 2 = artist, 3 = song
        self.name = name
        self.themeType = themeType
        self.numWorkouts = numWorkouts
        self.themeID = themeID
        self.timesUsed = timesUsed

    def __eq__(self, other)
        # You can implement the logic for equality here
        return (self.name, self.themeType, self.numWorkouts, self.themeID) ==\
               (other.name, other.themeType, other.numWorkouts, other.themeID)

請注意,我將屬性包裝在元組中,然后比較了元組的可讀性,但是您也可以一一比較屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM