python - 查看简单的 Python 类

标签 python

我有一个任务要创建一个代码,该代码创建一个类、两个函数和一个子类:The questions

我在这里做了

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"

Error msg

我阅读了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/

相关文章:

python - adsdb 插入

python - 使用 sudo python 打开终端

python - python 正则表达式中的字素支持

python - 如何调试通过单元测试部分覆盖但在重用时产生错误结果的 Python 代码?

python - 使用 pandas 将字符串替换为另一列中的相应字符串

python - 以特定字符开头的字符串计数

python - Reportlab 和 Fontawesome 字体

python - Scrapy LinkExtractor - 限制每个 URL 抓取的页面数量

python - Flask API 回调监听器

python - 如果值落在某个范围内,则根据另一列的条件创建新列