多级继承python - 'CheckingAccount'对象没有属性'balance'

时间:2018-05-09 05:52:16

标签: python

我正在开发一个python项目。当我只有一个级别的继承时,一切都运行良好但是一旦我添加了SavingAccountCheckingAccount,它应该是BankAccount的孩子,这是客户的孩子我开始得到以下内容错误:'CheckingAccount' object has no attribute 'balance'

我以为我会像第一层那样做第二层继承,但也许我必须要失踪。在此先感谢您的帮助!

class Customer:
    def __init__(self,firstName, lastName, social):
        self.firstName = firstName 
        self.lastName = lastName 
        self.social = social 

    def setfirstName(self,firstName):
        self.firstName = firstName

    def setlastName(self,lastName):
        self.lastName = lastName

    def __str__(self):
        self.name = "{},{} (SSN:{})".format(self.firstName, self.lastName,self.social)
        return self.name 


class BankAccount(Customer):
    from random import randint
    n = 10
    range_start = 10**(n-1)
    range_end = (10**n)-1
    accountNumber = randint(range_start, range_end)

    def __init__(self,customer,balance = 0):
        self.customer = customer
        self.balance = balance 

    def setCustomer(self,customer,accountNumber):
        self.customer = customer
        self.accountNumber = accountNumber 

    def getCustomer(self,customer,accountNumber):
        return self.customer, self.accountNumber

    def deposit(self, amount):
        self.balance = self.balance + amount
        return self.balance

    def withdrawal(self, amount):
        self.balance = self.balance - amount
        return self.balance

    def __str__(self):
        customer = "{} account number: {}, balance: ${}".format(self.customer,self.accountNumber,self.balance)
        return customer 
class CheckingAccount(BankAccount):
    def __init__(self, bankAccount):
        self.bankAccount = bankAccount



    def applyAnnualInterest(self):
        excess = self.balance - 10000
        if excess > 0:
            interest = (excess * .02)
            self.balance = self.balance + interest
            return self.balance
        else:
            return self.balance


class SavingAccount(BankAccount):
    def __init__(self, bankAccount):
        self.bankAccount = bankAccount


    def applyAnnualInterest(self):
        interest = (self.balance * .05)
        self.balance = self.balance + interest
        return self.balance


def main():

    alin = Customer('Alin', 'Smith', '111-11-1111')
    mary = Customer('Mary', 'Lee', '222-22-2222')
    alinAccnt = CheckingAccount(alin)
    maryAccnt = SavingAccount(mary)

    alinAccnt.deposit(20000)
    print(alinAccnt)

1 个答案:

答案 0 :(得分:1)

您需要初始化父级;尝试:

class CheckingAccount(BankAccount):
    def __init__(self, bankAccount):
        super(CheckingAccount, self).__init__()
        self.bankAccount = bankAccount

不要忘记中级班!

class BankAccount(Customer):
    def __init__(self,customer,balance = 0):
        super(BankAccount, self).__init__()
        self.customer = customer
        self.balance = balance 

这将确保调用父构造函数。