回顾简单的Python类

时间:2016-03-22 16:46:28

标签: python

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

我在这做了什么

template <class A, class B>
bool IsSameClass() {
  return is_same<A, B>::value;
}
int main()
{
  bool ret =    IsSameClass<P,C>();
}

但是在跑步时,我收到了这个错误:

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)

Error msg

我读了AssetionError,所以我尝试了无效的交易&#39;而不是&#34;无效的交易&#34;,也没有运气

但令我感到困惑的是,该程序似乎在我的系统IDE上正常运行,所以我不认为这是语法错误,但我不知道它可能是什么。

我需要帮助弄清楚我做错了什么。

1 个答案:

答案 0 :(得分:1)

AssertionError正在发生,因为您正在将字符串'"invalid transaction"'与字符串'invalid transaction'进行比较。第一个字符串的第一个字符是";第二个字符串的第一个字符是i

(虽然我原本期望引发语法错误,因为转义引号\&#34;像这样\&#34;字符串之外无效,但来自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