首页 > 解决方案 > 如何在班级之间切换

问题描述

我正在为我的作业编写关于“银行”的代码,我需要创建抽象类Account和两个子类CheckingAccountSavingAccount. CheckingAccount我这样做是为了加钱,显示余额等。但我还需要在和之间切换SavingAccount

from abc import ABC, abstractmethod


class Account(ABC):

    @abstractmethod
    def add_money(self):
        pass

    @abstractmethod
    def balance(self):
        pass

    @abstractmethod
    def take_money(self):
        pass


class CheckingAccount(Account):
    def __init__(self, money):
        self.__money = money

    def add_money(self, y):
        self.__money += y

    def balance(self):
        return self.__money

    def take_money(self, y):
        self.__money -= y

class SavingsAccount(Account):
    def __init__(self, money):
        self.__money = money

    def add_money(self, y):
        self.__money += y

    def balance(self):
        return self.__money

    def take_money(self, y):
        self.__money -= y

if __name__ == '__main__':
    z = 0
    j = 0
    print("Which account you want to choose?")
    j = int(input("1- Checking\n2- Savings"))
    if j == 1:
        cc = CheckingAccount(0)
        while z != 4:

            print("1- Balance\n2- Add money\n3- Take money\n4- Exit\n5- Switch Account")
            z = int(input("Choose operation: "))

            if z == 1:
                print(cc.balance())

            if z == 2:
                y = int(input("Money: "))
                cc.add_money(y)

            if z == 3:
                y = int(input("Take money: "))
                cc.take_money(y)


    if j == 2:
        cc = SavingsAccount(0)
        while z != 4:

            print("1- Balance\n2- Add money\n3- Take money\n4- Exit\n5- Switch Account")
            z = int(input("Choose operation: "))

            if z == 1:
                print(cc.balance())

            if z == 2:
                y = int(input("Money: "))
                cc.add_money(y)

            if z == 3:
                y = int(input("Take money: "))
                cc.take_money(y)

我希望能够在不丢失内存的情况下在帐户之间切换,我的意思是如果我向Checking帐户添加 50 并切换SavingsAccount回我仍然可以看到余额为 50。

请给我一些想法

标签: python-3.x

解决方案


我建议添加方法,例如toSavingAccount()CheckingAccount类上,返回一个SavingAccount.

或者,您也可以使用@classmethods,它有点像附加构造函数。你可以在这里阅读一些关于它们的信息

这允许调用,例如

my_savings_account = SavingAccount.fromCheckingAccount(my_checking_account)

或者

my_savings_account = my_checking_account.toSavingAccount()

无论你如何命名这些方法,都取决于你,但你明白了。


推荐阅读