在前几天我参考教程中的“函数课程”写了银行的“存取款系统”里程碑,今天用 python 函数做出一个简单小应用啦!,这次我参考教程中的“面向对象”的知识写了银行“存取款系统”,这里侧重点是要建立两个“对象”:
- class Bank(object):
- class User(object):
其它代码参考了原来函数中的代码《里程碑,今天用 python 函数做出一个简单小应用啦!》,并使用了函数装饰器的方法。
具体实现代码如下:
import datetime
def valideate(func):
def wrapper(self,*args,**kwargs):
amount = str(args[0])
index = amount.index(".")
if len(amount) - index - 1 > 1:
print("输入格式有误,小数点最多保留两位")
else:
func(self,*args,**kwargs)
return wrapper
class Bank(object):
account_log = []
def __init__(self,name):
self.name = name
@valideate
def deposit(self,amount):
user.balance += amount
self.write_log("存入",amount )
@valideate
def withdrawal(self,amount):
if amount > user.balance:
print("余额不足")
else:
user.balance -= amount
self.write_log("取出",amount)
def write_log(self,type,amount ):
now = datetime.datetime.now()
create_time = now.strftime("%Y-%m-%d %H:%M:%S")
data = [self.name,user.username,create_time,type,amount,f'{user.balance:.2f}']
Bank.account_log.append(data)
class hantang(Bank):
def __init__(self,name):
self.name = name
class jianshe(Bank):
def __init__(self,name):
self.name = name
class User(object):
def __init__(self,username,balance):
self.username = username
self.balance = balance
def print_log(self):
print(Bank.account_log)
#bank = Bank("hantang")
bank = hantang("汉唐帝国银行")
user = User("Andy",1000)
def show_menu():
menu = """
操作菜单:
0:退出;
1:存款;
2:取款;
3:查看记录;
"""
print(menu)
while True:
show_menu()
num = int(input("请根据菜单编号输入:"))
if num == 0:
print("你已退出系统")
break
elif num == 1:
print("存款")
amount = float(input("请输入存款金额:"))
bank.deposit(amount)
print(f"当前余额是{user.balance:.2f}")
elif num == 2:
print("取款")
amount = float(input("请输入取款金额:"))
bank.withdrawal(amount)
print(f"当前余额是{user.balance:.2f}")
elif num == 3:
print("查看记录")
user.print_log()
else:
print("输入有误")
运行输出结果: