多层次继承python-';核对账户';对象没有属性';余额';
我正在从事一个python项目。当我只有一个继承级别时,一切都很好,但一旦我添加了多层次继承python-';核对账户';对象没有属性';余额';,python,Python,我正在从事一个python项目。当我只有一个继承级别时,一切都很好,但一旦我添加了SavingAccount和CheckingAccount这两个帐户,它们应该是客户的子帐户BankAccount的子帐户,我开始出现以下错误:“CheckingAccount”对象没有属性“balance” 我以为我会做第二层的继承和第一层一样,但也许我一定错过了。提前感谢您的帮助 class Customer: def __init__(self,firstName, lastName, social)
SavingAccount
和CheckingAccount
这两个帐户,它们应该是客户的子帐户BankAccount
的子帐户,我开始出现以下错误:“CheckingAccount”对象没有属性“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)
您需要初始化家长;尝试:
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
这将确保父构造函数也被调用