【问题标题】:class dictionary not updating [closed]类字典不更新[关闭]
【发布时间】:2018-09-14 17:01:35
【问题描述】:

我对 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()   

【问题讨论】:

  • 请提供您的问题的最小示例,您期望什么结果以及您有什么结果
  • 更新了! @CorentinLimier
  • 这不是minimal reproducible exampleself 模块来自哪里?这是一个非常奇怪和令人困惑的模块名称!该类中发生了一些奇怪的事情,例如global idict,并且一些方法缺少它们的self arg。
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。您给定的代码无法运行(self 包丢失),并且似乎需要用户输入才能显示错误。它根本不是最小的。
  • 好的,很抱歉@Prune

标签: python python-3.x dictionary


【解决方案1】:

嘿,伙计,我每天只有这么多时间花在这上面,但我设计了一个更好的框架供你使用,尝试使用这里的元素来处理和修改它,它的骨架应该对你有所帮助使用此特定代码完成所有目标。当我有时间只想给你一些玩的时候,我会回来更新更多!享受吧!

class Account:
    """set stuff"""

    def __init__(self):
        self.accounts = []

    def set_name(self):
        print(self.accounts)
        self.name = input("Enter the name of the Account Owner: ")
        self.accounts.append(self.name)
        print(self.accounts)

    def set_balance(self):
        self.balance = int(input("Enter Starting Balance: "))

    def deposit_amount(self):
        self.deposit = int(input("Enter Deposit amount: "))
        self.balance += self.deposit

    def withdrawl(self):
        self.withdraw = int(input("Enter Withdrawl Amount: "))
        self.balance -= self.withdraw

    def close_account(self):
        name = input("Enter the Account Name: ")
        if name in self.accounts:
            self.accounts.remove(name)
        else:
            print("Account not Found.")
            self.imenu()

    def imenu(self):
        print("\n1. Get Account Balance\n"
              "2. Deposit\n"
              "3. Withdraw\n"
              "4. Close Account\n"
              "5. Exit\n")
        choice = -1
        while choice not in range (1, 6):
            try:
                choice = int(input("Enter your choice: "))
            except ValueError:
                continue
        if choice == 1:
            print(self.balance)
            self.imenu()
        if choice == 2:
            self.deposit_amount()
            print("Money added")
            self.imenu()
        elif choice == 3:
            self.withdrawl()
            self.imenu()
        elif choice == 4:
            individual.close_account()
            return
        elif choice == 5:
            return

class Individual(Account):
    pass

class Business(Account):

    def savings(self):
        self.savings = 0

    def savings_deposit(self):
        self.s_deposit = int(input("Enter Deposit amount to Savings: "))
        self.savings += self.s_deposit


while True:
    print("\nAre you ready to open/access an account? 1 = Yes, 3 = No")
    ans = 5
    while ans not in range(1,2):
        try:
            ans = int(input("Enter either 1 or 2: "))
        except ValueError:
            continue

    print("\nWelcome to the Bank!")
    print("\nSelect and option from the Menu")
    print("1. Open Individual Account\n"
          "2. Open a Business Account\n"
          "3. Check Indiviudal Account\n"
          "4. Check Business ACcount\n"
          "5. Exit")
    select = -1
    while select not in range(1, 6):
        try:
            select = int(input("Please enter your selection: "))
        except ValueError:
            continue

    if select == 1:
        print("\nCreating Individual Account...")
        individual = Individual()
        individual.set_name()
        individual.set_balance()

    elif select == 2:
        print("\nCreating Business Account...")
        business = Business()
        business.set_name()
        business.set_balance()

    elif select == 3:
        print("\nLoading Individual Accounts...")
        name = input("Enter your Name: ")
        if name in individual.accounts:
            print("\nYour account was found! Proceeding...")
            individual.imenu()



    elif select == 4:
        print("\nLoading Business Accounts...")
        name = input("Enter name of Business: ")
        if name in business.accounts:
            print("Your account was found. Proceeding...")
            business.imenu()
        else:
            print("Account not found.")

    elif select == 5:
        print("Thank you for using Bank, Have a Nice Day!")
        break

【讨论】:

  • 遗憾的是仍然没有更新账户余额:(
  • 看一看,尝试推理一下这个方向,然后把它变成你自己的!
  • 啊哈看起来干净多了!我喜欢它,我肯定会看到我还能用这个做什么!唯一的问题是字典会很好,因为它可以有一个键和一个值(帐户所有者和余额),但仍然感谢您的帮助!
  • 干杯!如果我有时间,我会多玩一些,祝你好运!我强烈推荐 Python Crash Course、Automate the Boring Stuff 和 Python the Hard Way 这两本书
  • 我修复了它,现在它工作得很好,感谢您!我很感激像你这样的人,非常感谢! @vash_the_stampede
【解决方案2】:

首先,您使用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,它包含所有帐户的全局映射。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    相关资源
    最近更新 更多