类字典不更新

时间:2018-09-14 17:01:36

标签: python python-3.x dictionary

我对python还是很陌生,所以请多多包涵。我正在用python练习类和对象,所以我开始了这个银行帐户类。银行帐户有两种类型:个人或企业。商业帐户从个人那里继承了一些行为,但是我还没有完全结束。

这里的问题是,每当我存入一定金额(例如50)时,字典都不会将值更新为相应的键(帐户持有人的姓名),我希望该值会更新每当有人提取或存入帐户时-例如:初始余额= 50存款= 50,dict将名称和余额更新为初始余额+存款

import sys
import self

#print a menu so user can pick
def menu():
    print("Welcome to Wells Fargo!")
    print("Lets get started!")
    print("1. Open Individual Account \n"
          "2. Open Business Account \n"
          "3. Check Individual Account \n"
          "4. Check Business Account \n"
          "5. Exit")
    #if user doesnt type number or 1,2,3 , throw error
    try:
      choice = int(input("Please enter your choice here: "))
    except ValueError:
      print("Oops! Looks like you didnt type something correct, please try again!")
    if choice == 1:
      print("Creating Individual account...")
      #create object representing account info
      #set name method
      individual.set_name(self)
      #set balance method
      individual.set_balance(self)
      #call menu
      menu()
    elif choice == 2:
      print("Creating Business account...")
      #create object representing account
      name = str(input("Enter your name here: "))
      start_balance = int(input("Enter the balance you want to start with: "))
      save = int(input("Enter how much you want to deposit in your savings account: "))
      #add object to list
      bacc = Business(name, start_balance, save)
      #call menu
      menu()

    elif choice == 3:
      print("Loading Individual Accounts..")
      #call check individual accounts method
      individual.check_accounts()
    elif choice == 4:
      print("Loading Business Accounts...")
      #call check business accounts method
      Business.check_accounts()
    elif choice == 5:
      #exit the program
      print("Thank you for using wells fargo, have a nice day!")
      sys.exit(0)

#ask user if ready
def prompt_user():
    try:
      ready = int(input("Are you ready to open/access a account?1=Yes,2=No"))
    except ValueError:
      print("Oops! You did not type something right, please retry!")
    else:
      menu()

#individual bank account class
class individual:
  #initialize defaults (name, balance, &ilst)
  def __init__(self, balance=0, transaction=0,name=''):
    self.balance = balance
    self.transaction = transaction
    self.name = name
    self.idict = {}

  #get the name of the account owner
  def set_name(self):
    self.name = str(input("Enter the name of the account owner here: "))
    #add name to dictionary
    idict[self.name] = 0

  #get balance user wants to start with
  def set_balance(self):
    self.balance = int(input("Enter how much money you want to deposit into your account: "))
    #if amount is less than 25, throw error
    if self.balance < 25:
      print("ERROR! Low Amount, must be greater than or equal to 25")
    #else add it to the dictionary
    else:
      idict[self.name] = self.balance

  global idict


  idict = {
    "John Adams": 5000,
    "Josh Adkins": 4000
  }

  #return object as a string , is this needed??
  def __str__(self):
    return str(self.name)

  #add money & calculate
  def __add__(self,other):
    balance = self.balance + other.balance
    transaction = self.transaction + other.transaction
    return balance + transaction

  #subtract money & calculate
  def __sub__(self, other):
    balance = self.balance + other.balance
    transaction = self.transaction + other.transaction
    return balance - transaction
    #return individual(self.name, self.balance)

  #return user balance
  def __int__(self):
    #search for user name
    for x,y in idict.items():
      if self.name in idict:
        print("fetching account balance...")
        print(int(self.balance))
        break;
      else:
        print("ERROR! Looks like you arent registered in our system!")
        individual.imenu()


  #individual account menu
  def imenu():
    #1. balance, 2. transactions(add, subtract) 3. close acc 4. exit 
    print("1. Get Account Balance \n"
          "2. Deposit $$ \n"
          "3. Withdraw $$ \n"
          "4. Close Account \n"
          "5. Exit")
    choice2 = int(input("Enter your choice here: "))
    if choice2 == 1:
      individual.__int__(self)
    elif choice2 == 2:
      add_money = int(input("Enter the amount here: "))
      sum1 = individual(self.balance, 0)
      sum2 = individual(self.balance, add_money)
      idict[self.name] = sum1.__add__(sum2)
      print("Money added!")
      individual.imenu()
    elif choice2 == 3:
      sub_money = int(input("Enter the amount here: "))
      individual.__sub__(self, sub_money)
    elif choice2 == 4:
      individual.close_account(self)
    elif choice2 == 5:
      print("Goodbye!")
      sys.exit(0)     



  #loop thru indiv acc(s)
  def check_accounts():
    #have user type in their name and check if they have an open account
    enter_name = str(input("Enter your name here: "))
    for key,value in idict.items():
      #check if name is in list
      if enter_name in idict:
        print("Your account was found! Proceeding...")
        individual.imenu()
      else:
        print("Looks like you dont have an individual account, please create one!")

  #close individual account
  def close_account(self):
    print("Type in your name to proceed with account deletion: ")
    try:
      #have user type in their name
      type_name = str(input("Type it here: "))
    except ValueError:
      #if user types anything other than name, throw error
      print("Looks like you typed something incorrect! Please retry!")
    #search business account dict , 
    for x,y in idict.items():
      #if the name is in the, dict remove it
      if type_name in idict:
        del[type_name]
      #if the name is not in the dict, redirect to menu
      else:
        print("Looks like you dont have an account! Please create one!")
        menu()

#call methods
prompt_user()   

1 个答案:

答案 0 :(得分:1)

首先,您使用self设置您的个人帐户。在Python中,术语self与其他语言中的this类似,指的是您正在使用的类的实例。因此,应该使用individual.set_name(self)而不是使用individual.set_name()

对于您的特定问题,它源于此方法:

def set_balance(self):
    self.balance = int(input("Enter how much money you want to deposit into your account: "))
    #if amount is less than 25, throw error
    if self.balance < 25:
        print("ERROR! Low Amount, must be greater than or equal to 25")
    #else add it to the dictionary
    else:
        idict[self.name] = self.balance\

您只能设置余额,而不考虑其中的余额。相反,您应该尝试这样做:

new_balance = int(input("Enter how much money you want to deposit into your account: "))
if (self.name in idict):
    idict[self.name] += new_balance
else:
    idict[self.name] = new_balance

这将把选定的金额添加到其中,或者添加到字典中。

顺便说一句,您应该避免在类方法中要求输入,因为这是糟糕的体系结构。而是给您的set_balance方法另一个名为amount的参数,并使用它代替您的输入。

我也建议不要重载__add____sub__,除非您对有意义的数学运算进行类比。在您的情况下,添加两个银行帐户以获得第三个帐户真的没有任何意义,所以这可能不是一个好主意。

然后是您的individual班。您如何将实例变量和全局变量混合在一起很奇怪。您的班级有namebalance之类的东西,我希望它们属于银行帐户类,然后是idict,其中包含所有帐户的全局映射。

我建议将此代码提交给代码审查委员会,因为其中存在很多问题,我认为您将从对代码的更详尽的批评中受益。