回顾简单Python类

回顾简单Python类,python,Python,我的任务是创建一个代码,创建一个类、两个函数和一个子类: 这是我在这里做的 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

我的任务是创建一个代码,创建一个类、两个函数和一个子类:

这是我在这里做的

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上运行得很好,所以我不认为这是一个语法错误,但我不知道还有什么可能


我需要帮助找出我做错了什么。

发生断言错误是因为您正在比较字符串
“无效事务”
和字符串
“无效事务”
。第一个字符串的第一个字符是
;第二个字符串的第一个字符是
i

(虽然我预计会出现语法错误,因为在字符串外转义引号“like this”是无效的,但IDE的消息表明发生了其他事情)

我同意其他评论者的观点——如果发生无效事务,方法
draw
抛出异常将更有意义。在单元测试中,您可以断言引发了此异常

下面是该方法的外观:

def withdraw(self, amt):
    if amt > self.balance:
        raise ValueError('Invalid transaction')
    else:
        self.balance = self.balance - amt

然后,在单元测试中,如果您使用的是unittest框架,那么可以使用assertRaises检查方法是否在应该时引发异常,断言几乎肯定是在寻找“无效事务”“完全没有引用。这似乎是一个设计非常糟糕的任务<代码>提款应在透支的情况下引发异常,而不是返回字符串。如果还没有引入异常,那么赋值应该局限于已经引入的概念。你能修复代码中的缩进吗?