【问题标题】:Create Account Object创建帐户对象
【发布时间】:2026-01-04 03:15:03
【问题描述】:

我的程序创建了一个 Account 对象,其帐户 ID 为 1122,余额为 20,000 美元,年利率为 4.5%。使用withdraw方法取出$2,500,deposit方法存入$3,000,打印id、余额、月利率、月利息。

我在下一部分遇到了问题,即我的程序还应该询问 id、余额和利率的起始值。然后它应该显示一个菜单,用户可以在其中修改他们的帐户。每次选择后,应显示适当的消息。然后应该会再次显示菜单。

示例菜单:

(1):显示 ID

(2):显示平衡

(3):显示年利率

(4):显示月利率

(5):显示每月利息

(6):取款

(7):存钱

(8):退出

如何修改我的代码以在用户输入的情况下正常运行?现在它正在工作,但我没有任何要求用户输入的代码。

这是我的代码:

main module:

from Account import Account

def main():
    updatedAccount = Account(1122,20000,4.5)
    updatedAccount.withdraw(2500)
    print("User ID : ", updatedAccount.id)
    print("Beginning Balance: ", updatedAccount.balance)
    print("Monthly Interest Rate: ", updatedAccount.monthly_interest_rate)
    print("Monthly Interest: ", updatedAccount.get_monthly_interest())

main()

帐户.py

class Account:

    def __init__(self, id, initial_balance=0, rate=4.5):
        self.id = id
        self.balance = initial_balance
        self.annual_interest_rate = rate

    @property
    def monthly_interest_rate(self):
        return self.annual_interest_rate / 12

    def get_monthly_interest(self):
        return self.balance * self.monthly_interest_rate

    def withdraw(self, amount):
        if self.balance < amount:
            raise ValueError(f"Overdraft, balance less than {amount}")

        self.balance -= amount

    def deposit(self, amount):
        self.balance +=amount

我已尝试为起始帐户值编写用户输入,但在使用它来创建帐户对象以及如何实现菜单时遇到了麻烦。

userid = float(input("Enter User ID: "))
InterestRate = float(input("Enter Interest Rate: "))
balance = float(input("Enter balance: "))

print("User ID is: ", userid)
print("Interest Rate: ", InterestRate)
print("Balance is: ", balance)

【问题讨论】:

  • 基本上你需要,在一个循环中,(1) 显示菜单选项,(2) 阅读用户的选择,(3) 做用户要求的事情。这是相当广泛的——如果出现更具体的问题,或者如果您有菜单代码并且可以明确指出其行为与您想要的行为有何不同,我建议您尝试上述方法并编辑帖子。

标签: python python-3.x


【解决方案1】:

您需要使用Account 的构造函数并提供您拥有的值

userid = float(input("Enter User ID: "))   // maybe use int() rather than float ? 
interestRate = float(input("Enter Interest Rate: "))
balance = float(input("Enter balance: "))

acc = Account(userid, balance, interestRate)

print(acc)

如果您重写 __str__ 方法,您只需调用 print(acc) 即可打印对象

// in Account class
def __str__(self):
    return f"ID {self.id},Bal {self.balance}, Rat {self.annual_interest_rate}"

菜单的简单方法可以是这样,在apply_actions中完成if/elif代码并在actions数组中以相同的顺序添加它们

def apply_actions(action, account):
    if action == 0:      # display ID
        print(f"Your id is {account.id}")
    elif action == 1:    # display balance
        print(f"Your balance is {account.balance}")
    # ...
    elif action == 6:
        to_deposit = float(input("How many money for the deposit ?"))
        account.deposit(to_deposit)
    elif action == 7:
        exit(1)
    else:
        print("Bad index")

if __name__ == '__main__':
    # ...
    acc = Account(userid, balance, interestRate)

    actions = ["Display ID", "Display Balance", "Deposit", "Exit"]
    while True:
        choice = int(input("Choose index in " + str(list(enumerate(actions)))))
        apply_actions(choice, acc)

【讨论】:

  • 谢谢,你能给我一个如何开始我的菜单的例子吗?
  • @LouisS。我已经编辑添加了一个小示例,但如果您需要更多,您可能会考虑尝试这样做,然后在 SO 上创建一个新问题,因为这是一个不同的目的
【解决方案2】:

您有两个问题,关于创建帐户,您通常使用用户输入来完成。

userid = float(input("Enter User ID: "))
InterestRate = float(input("Enter Interest Rate: ")) 
balance = float(input("Enter balance: "))

user_account = Account(userid, balance, InterestRate)

现在,对于您的菜单,您可以创建一个简单的函数来显示您的菜单并将用户发送到每个函数,并在用户完成后将它们发送回您的菜单。

def menu():
    possibilities = [(1, "Display ID", "id"), (2, "Display balance", "balance")]
    while True:
        for possibility in possibilities:
            print(f"({possibility[0]}): {possibility[1]}")
        User_input = int(input("Please select an option"))
         if User_input in [pos[0] for pos in possibilities]:
              option, name, attrib = [pos for pos in possibilities if pos[0] == User_input]
              print(getattrib(Account, attrib)) 
         else:
             print("Option not avaliable")

【讨论】:

  • “将用户发送到操作”是什么意思?您如何为菜单的每个部分指定一个电话号码,以便当用户输入该号码时,它会显示所选选项?
  • 发送用户到操作将调用链接的函数。例如:显示 ID。您可以使用元组列表,例如 [(0, 'Display ID', display_ID),...],格式为数字、名称、函数。然后您可以简单地循环遍历它,并根据用户输入对其进行过滤。
  • 哦,好的。您能否给我一个实际示例,说明在“If User_Input in possible:”之后我必须输入的格式?因为当我输入元组列表时它给我一个帐户错误。
  • @LouisS。这远不是一个好的实现,但你明白了。