python-3.x - 如何在班级之间切换
问题描述
我正在为我的作业编写关于“银行”的代码,我需要创建抽象类Account
和两个子类CheckingAccount
和SavingAccount
. 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。
请给我一些想法
解决方案
我建议添加方法,例如toSavingAccount()
在CheckingAccount
类上,返回一个SavingAccount
.
或者,您也可以使用@classmethod
s,它有点像附加构造函数。你可以在这里阅读一些关于它们的信息
这允许调用,例如
my_savings_account = SavingAccount.fromCheckingAccount(my_checking_account)
或者
my_savings_account = my_checking_account.toSavingAccount()
无论你如何命名这些方法,都取决于你,但你明白了。
推荐阅读
- python - 多处理中的python泡菜字符串
- angular - Spring MVC 和 Angular - 原因:缺少 CORS 标头“Access-Control-Allow-Origin”
- java - 是否可以从上到下链接覆盖的方法调用?
- r - stat_smooth 和 geom_ribbon 之间的不良交互
- c# - 如何设置权限以在 Xamarin 表单应用程序中列出目录
- javascript - 使用父组件将初始值传递给子组件,而不依赖于状态 ReactJS
- python - 使用python将数据导入MYSQL的问题(错误代码:“SQL语句中没有使用所有参数)
- mysql - sql left join,您将右侧字段实例组合成单个 csv 列结果
- jenkins - Kubernetes yaml 的服务器端验证
- elasticsearch - Elasticsearch 查询的问题 - [range] 格式错误的查询,预期为 [END_OBJECT] 但找到了 [FIELD_NAME]