我想访问父类变量' bal'从子类中进行更改。
我尝试使用没有init()函数的子类,但它表明存款不是AccountHolder的属性,它是父类。
class AccountHolder(object):
total = 0
def __init__(self, acc_no, name, age, bal):
self.acc_no = acc_no
self.name = name
self.age = age
self.bal = bal
AccountHolder.total = AccountHolder.total + 1
def __repr__(self):
return "\nName: {}\nBalance: {:10.2f}\n".format(self.name, self.bal)
def update(self, new_bal):
print"Old balance:", self.bal
self.bal = new_bal
print"New balance:", self.bal
def totalAccHolders():
print"Total no of account holders=", AccountHolder.total
totalAccHolders = staticmethod(totalAccHolders)
class savingah(AccountHolder):
def __init__(self, acc_no, name, age, bal, dep):
super().__init__(acc_no, name, age, bal)
self.dep=dep
def deposit(AccountHolder, new_bal):
print"Old balance:", AccountHolder.bal
self.bal += dep
print"New balance:", AccountHolder.bal
class loanah(AccountHolder):
def __init__(self, acc_no, name, age, bal, wdraw):
super().__init__(acc_no, name, age, bal)
self.wdraw=wdraw
def withdraw(self, new_bal):
print"Old balance:", self.bal
self.bal -= wdraw
print"New balance:", self.bal
listAcc = []
b = savingah()
while(True):
print("\nMENU")
print"1. Create a new AccountHolder"
print"2. Update AccountHolder balance"
print"3. Saving update"
print"4. Loan update"
op = int(input("Enter option - "))
if op==1:
listAcc.append(AccountHolder(int(input("Enter AccNo: - ")),
input("Enter Name: "),
int(input("Enter age: ")),
float(input("Enter balance: "))))
print(listAcc[-1])
AccountHolder.totalAccHolders()
elif op==2:
s = input("Enter Account number - ")
for a in listAcc:
if s == a.acc_no:
bal = float(input("Enter new balance - "))
a.update(bal)
elif op==3:
s = input("Enter Account number - ")
for a in listAcc:
if s == a.acc_no:
bal = float(input("Enter amount to be deposited - "))
b.deposit(bal)
elif op==4:
s = input("Enter Account number - ")
for a in listAcc:
if s == a.acc_no:
bal = float(input("Enter amount to be withdrawn - "))
a.withdraw(bal)
else:
print "Invalid input\n"
break
我使用此代码时遇到错误,如果从saveah中删除init函数,则会收到错误,指出类AccountHolder init属性不存在 -
[student@PC-16 ~]$ python vexp6.py
Traceback (most recent call last):
File "vexp6.py", line 33, in <module>
b = savingah()
TypeError: __init__() takes exactly 6 arguments (1 given)
任何帮助将不胜感激,谢谢。