我需要以下帮助。因此,该项目是python中的一个程序,用于管理和操作当时可能存在或不存在的10个银行账户。我在涉及资金转移的一个部分遇到了麻烦。所有信息都存储在一个类中。该类存储帐号名称地址和帐户余额。
def transtransfer():
amount = float(input("Transfer Amount (Integer): "))
account1 = input("Account you want to transfer funds from (Account number): ")
account2 = input("Account you want to transfer funds to (Account number): ")
while amount < 0:
print("Transfer amount must be positive: ")
amount = input("Transfer Amount: ")
while
语句只是一个检查,以确保它们不能输入低于0的值。但我需要某种方式允许用户动态选择一个类变量进行编辑以供日后使用。
以下代码是我正在使用的代码,我通过调用银行类手动初始化所有帐户:
class bank:
def __init__(self, accnum, accname, accadd, accbal):
self.accnum = accnum
self.accname = accname
self.accadd = accadd
self.accbal = accbal
def printclass(self):
print("Account Number: " + str(self.accnum))
print("Account Name: " + str(self.accname))
print("Account Address: " + str(self.accadd))
print("Account Balance: " + str(self.accbal))
def printclassid(self):
print("Account Name: " + self.accname)
print("Account Number: " + self.accnum)
acc1 = bank('0', '0', '0', '0')
acc2 = bank('0', '0', '0', '0')
acc3 = bank('0', '0', '0', '0')
acc4 = bank('0', '0', '0', '0')
acc5 = bank('0', '0', '0', '0')
acc6 = bank('0', '0', '0', '0')
acc7 = bank('0', '0', '0', '0')
acc8 = bank('0', '0', '0', '0')
acc9 = bank('0', '0', '0', '0')
acc10 = bank('0', '0', '0', '0')
答案 0 :(得分:0)
假设您的帐户acc1
,acc2
等位于名为accounts
的列表中。然后,您可以为这些帐户构建索引。
accounts_by_number = {acc.accnum:acc for acc in accounts}
您现在可以动态编辑数字:
def transfer(fromacct, toacct, amount):
try:
# disallow negative transfers
if amount < 0:
print("Bad amount", amount)
return False
# validate from has the funds
f_new = accounts_by_number[fromacct].accbal - amount
if f_new > 0:
# calculate new balance
o_new = accounts_by_number[toacct].accbal + amount
# commit the transfer
accounts_by_number[fromacct].accbal = f_new
accounts_by_number[toacct] = t_new
return True
else:
print("insufficient funds")
return False
except KeyError as e:
print("Bad account number:", e.args[0])
return False