我有一个任务要创建一个代码,该代码创建一个类、两个函数和一个子类:
我在这里做了
class BankAccount:
def __init__(self, startBal):
self.balance = startBal
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self, amt):
if amt > self.balance:
return ('"invalid transaction"')
else:
self.balance = self.balance - amt
class MinimumBalanceAccount(BankAccount):
def __init__(self, bal):
super(MinimumAccountBalance, self).__init(bal)
但是在运行时,我收到此错误:
{"finished": true, "success": [{"fullName": "test_balance", "passedSpecNumber": 1}, {"fullName": "test_deposit", "passedSpecNumber": 2}, {"fullName": "test_sub_class", "passedSpecNumber": 3}, {"fullName": "test_withdraw", "passedSpecNumber": 4}, {"fullName": "test_balance", "passedSpecNumber": 5}, {"fullName": "test_deposit", "passedSpecNumber": 6}, {"fullName": "test_sub_class", "passedSpecNumber": 7}, {"fullName": "test_withdraw", "passedSpecNumber": 8}], "passed": false, "started": true, "failures": [{"failedSpecNumber": 1, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 47, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}, {"failedSpecNumber": 2, "fullName": "test_invalid_operation", "failedExpectations": [{"message": "Failure in line 23, in test_invalid_operation\n self.assertEqual(self.my_account.withdraw(1000), \"invalid transaction\", msg='Invalid transaction')\nAssertionError: Invalid transaction\n"}]}], "specs": {"count": 10, "pendingCount": 0, "time": "0.000052"}}
"invalid transaction"
"invalid transaction"
我阅读了AssetionError,所以我尝试了“无效交易”而不是“无效交易”,但也没有运气
但令我困惑的是,该程序似乎在我的系统 IDE 上运行良好,所以我不认为这是语法错误,但我不知道还可能是什么。
我需要帮助找出我做错了什么。
最佳答案
发生 AssertionError 是因为您将字符串 '"invalid transaction"'
与字符串 'invalid transaction'
进行比较。第一个字符串的第一个字符是 "
;第二个字符串的第一个字符是 i
。
(虽然我预计会引发语法错误,因为在字符串外部转义引号“like this”是无效的,但来自 IDE 的消息表明发生了其他情况)
我同意其他评论者的观点——如果发生无效交易,您的方法withdraw
抛出异常会更有意义。在您的单元测试中,您可以断言引发了此异常。
该方法可能如下所示:
def withdraw(self, amt):
if amt > self.balance:
raise ValueError('Invalid transaction')
else:
self.balance = self.balance - amt
然后在你的单元测试中,如果你使用的是unittest框架,你可以使用assertRaises来检查该方法是否在应该时引发异常 https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises
关于python - 查看简单的 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36160376/