__init__()方法只需要1个位置参数,但是给出了2个。

5

我已经阅读了其他帖子关于这个错误的内容,我认为我解决了问题,但是我仍然遇到了麻烦。

我已经在适当的位置包含了必要的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)

6
BankAccount.__init__方法只接受self作为参数,但你同时还传入了initBal参数。因此,你要么将BankAccount.__init__改为接受初始余额的参数,要么停止传递初始余额参数。 - Tadhg McDonald-Jensen
可能是重复的问题:TypeError: __init__() takes 1 positional argument but 4 were given - Adam Van Prooyen
3个回答

3
您可能想要重新定义BankAccount,如下所示:
class BankAccount(object):
    def __init__(self, init_bal=0):
        self.balance = init_bal

     # ...

1
您可以将BankAccount的构造函数编写为:
def __init__(self, initbal=0)
    self.balance = initbal

谢谢你们俩,我已经按照建议进行了修改,现在一切都正常工作了。 - c_l0426

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 = {}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接