[英]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将执行以下操作。
它将首先尝试调用obj1.__eq__(obj2)
,这是在obj1
类中定义的方法,该方法应确定相等性的逻辑。
如果此方法不存在,或者返回NotImplemented
,那么Python将回退到调用obj2.__eq__(obj1)
。
如果仍然不确定,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.