Python断言错误创建类

2024-05-01 22:10:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类用户和一个类主题。用户类可以创建主题,将主题添加到主题的字典中,并且应该能够返回主题的字典。我对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)

但我明白了- 回溯(最近一次呼叫): 文件“/测试/测试用户.py,第52行,测试中 自我评价(usr1.createTheme(“主题”,2,5,1,0),主题1) 断言错误:!=

我不知道我做错了什么,谁能帮我一下吗?你知道吗

(另外,我在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]

Tags: 用户nameself主题字典def逻辑theme
1条回答
网友
1楼 · 发布于 2024-05-01 22:10:37

发生了什么事

当试图确定两个对象是否相等时,比如说obj1 == obj2,Python将执行以下操作。你知道吗

  1. 它将首先尝试调用obj1.__eq__(obj2),这是一个方法 在obj1类中定义,该类应确定 平等。

  2. 如果此方法不存在,或返回NotImplemented,则 Python返回调用obj2.__eq__(obj1)

  3. 如果这仍然不是决定性的,Python将返回id(obj1) == id(obj2), i、 它会告诉你两个值在内存中是否是同一个对象。

在测试中,Python必须退回到第三个选项,并且对象是类Theme的两个不同实例。你知道吗

你想发生什么

如果您希望对象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)

注意,我将属性包装在元组中,然后比较元组的可读性,但是您也可以逐个比较属性。你知道吗

相关问题 更多 >