__init __()需要1个位置参数但是2个被赋予

时间:2016-10-28 20:06:43

标签: python

我已阅读其他有关此错误的帖子,我认为我解决了这个问题,但我仍然遇到问题。

我已经包含了必要的' self'在适当的空间,但我仍然 收到错误:

Traceback (most recent call last):
  File "...", line 30, in <module>
    JohnSmith = CheckingAccount(20000)
  File "...", line 18, in __init__
    BankAccount.__init__(self, initBal)
TypeError: __init__() takes 1 positional argument but 2 were given
class BankAccount (object):
        # define class for bank account
        def __init__ (self):
            # initialize bank account w/ balance of zero
            self.balance = 0
        def deposit (self, amount):
            # deposit the given amount into account
            self.balance = self.balance + amount
        def withdraw (self, amount):
            # withdraw the given amount from account
            self.balance = self.balance - amount
        def getBalance (self): 
            # return account balance
            return self.balance

class CheckingAccount (BankAccount):
    def __init__ (self, initBal):
        BankAccount.__init__(self, initBal)
        self.checkRecord = {}
    def processCheck (self, number, toWho, amount):
        self.withdraw(amount)
        self.checkRecord[number] = (toWho, amount)
    def checkInfo (self, number):
        if self.checkRecord.has_key(number):
            return self.checkRecord [ number ]
        else:
            return 'No Such Check'

# create checking account
JohnSmith = CheckingAccount(20000)
JohnSmith.processCheck(19371554951,'US Bank - Mortgage', 1200)
print (JohnSmith.checkInfo(19371554951))
JohnSmith.deposit(1000)
JohnSmith.withdraw(4000)
JohnSmith.withdraw(3500)

3 个答案:

答案 0 :(得分:2)

您可能希望将BankAccount重新定义为

class BankAccount(object):
    def __init__(self, init_bal=0):
        self.balance = init_bal

     # ...

答案 1 :(得分:1)

您可以将BankAccount的构造函数编写为

def __init__(self, initbal=0)
    self.balance = initbal

答案 2 :(得分:1)

class CheckingAccount(BankAccount):
    def __init__(self, initBal):
        super().__init__()
        self.balance = initBal
        self.checkRecord = {}

这样的事情会让你开始。我也改变了

if self.checkRecord.has_key(number):

if number in self.checkRecord:

您永远不会使用initBal或将其分配给变量,我认为它应该是self.balance

我在这里也使用了super,它只适用于python 3.它允许你在将来更改BankAccount的名称,而无需重构代码。如果你可以使用它,我强烈推荐它,这是一个很好的做法。否则解决方案是

class CheckingAccount(BankAccount):
    def __init__(self, initBal):
        BankAccount.__init__(self)
        self.balance = initBal
        self.checkRecord = {}