Python實現(xiàn)的銀行系統(tǒng)模擬程序完整案例
本文實例講述了Python實現(xiàn)的銀行系統(tǒng)模擬程序。分享給大家供大家參考,具體如下:
銀行系統(tǒng)模擬程序
1、概述
使用面向?qū)ο笏枷肽M一個簡單的銀行系統(tǒng),具備的功能:管理員登錄/注銷、用戶開戶、登錄、找回密碼、掛失、改密、查詢、存取款、轉(zhuǎn)賬等功能。
編程語言:python。
2、目的
通過這個編程練習(xí),可以熟悉運用面向?qū)ο蟮乃枷雭斫鉀Q實際問題,其中用到的知識點有類的封裝、正則表達式、模塊等。
3、體會
在編寫這個程序時,實際上的業(yè)務(wù)邏輯還是要考慮的,比如修改密碼時需要輸入手機號、身份證號等。在進行類的封裝時,實際上還是用面向過程的思想把一些基本的業(yè)務(wù)邏輯編寫成函數(shù),對一些重復(fù)使用的代碼也可以封裝成函數(shù)(就是自己造適合這個業(yè)務(wù)的輪子,實際開發(fā)中很多底層的函數(shù)是不用自己再次去實現(xiàn)的,可以直接調(diào)用),這些都是一些底層的封裝,然后在實現(xiàn)主要業(yè)務(wù)時上就可以調(diào)用類中的方法實現(xiàn),這時只需關(guān)注業(yè)務(wù)邏輯就好了。
使用面向?qū)ο蟮乃枷脒M行編程,考慮的點是:實現(xiàn)一個功能,有哪些方法可以讓我進行調(diào)用(指揮者)。
使用面向過程的思想進行編程,考慮的點是:實現(xiàn)一個功能,我需要實現(xiàn)哪些方法(執(zhí)行者)。
編寫這個程序還用到一個很重要的概念,就是對程序進行模塊化。模塊化的好處是可以更好的對程序進行維護,條理也更清晰。
4、代碼
源碼Github地址:https://github.com/liangdongchang/pyBankSystem.git
1、bankSystem.py文件
from view import View
from atm import ATM
from person import Person
def func(view,atm,per):
view.funcInterface()
choice = input("請選擇您要辦理的業(yè)務(wù):")
if choice == '1':
return per.checkMoney(atm)
elif choice == '2':
return per.saveMoney(atm)
elif choice == '3':
return per.getMoney(atm)
elif choice == '4':
return per.transferMoney(atm)
elif choice == '5':
return per.changePassword(atm)
elif choice == '6':
return per.unlockAccount(atm)
elif choice == '7':
return per.closeAccount(atm)
elif choice == 'T':
if per.exit(atm):
return True
else:
print("輸入有誤!")
def main():
# 管理員登錄名為'admin',密碼為'123'
view = View("admin",'123')
view.initface()
atm = ATM()
view.login()
per = Person()
while True:
view.funcInit()
choice = input("請選擇您要辦理的業(yè)務(wù):")
if choice == '1':
per.newAccount(atm)
elif choice == '2':
if per.login(atm):
while True:
if func(view,atm,per) == None:
continue
else:
break
elif choice == '3':
per.findBackPassword(atm)
elif choice == '4':
per.lockAccount(atm)
elif choice == 'T':
if per.exit(atm):
# 管理員注銷系統(tǒng)
if view.logout():
return True
else:
print("輸入有誤!")
if __name__ == '__main__':
main()
2、card.py文件:
'''
卡:
類名:Card
屬性:卡號【6位隨機】 密碼 余額 綁定的身份證號 手機號
'''
class Card(object):
def __init__(self, cardId, password, money,identityId,phoneNum,cardLock='False'):
self.cardId = cardId
self.password = password
self.money = money
self.identityId = identityId
self.phoneNum = phoneNum
self.cardLock = cardLock
3、readAppendCard.py文件:
'''
功能:讀取文件cardInfo.txt的信息
方法:讀、寫、刪
'''
from card import Card
import json
# 讀
class ReadCard(Card):
def __init__(self, cardId='', password='', money=0, identityId='', phoneNum='', cardLock=''):
Card.__init__(self, cardId, password, money, identityId, phoneNum, cardLock)
def dict2Card(self, d):
return self.__class__(d["cardId"], d["password"], d["money"],d["identityId"],d["phoneNum"], d["cardLock"])
def read(self):
# card對象轉(zhuǎn)為字典
with open("cardinfo.txt","r",encoding="utf-8") as fr:
cards = []
for re in fr.readlines():
cards.append(self.dict2Card(eval(re)))
return cards
# 寫
class AppendCard(Card):
def __init__(self):
Card.__init__(self, cardId = '', password = '', money = 0, identityId = '', phoneNum = '', cardLock='')
def card2Dict(self,card):
return {"cardId": card.cardId, "password": card.password,
"money": card.money, "identityId": card.identityId,
"phoneNum": card.phoneNum, "cardLock": card.cardLock
}
def append(self,card,w= 'a'):
# 默認(rèn)是追加,如果w='w'就清空文件
if w == 'w':
with open("cardinfo.txt", "w", encoding="utf-8") as fa:
fa.write('')
else:
with open("cardinfo.txt", "a", encoding="utf-8") as fa:
json.dump(card, fa, default=self.card2Dict)
fa.write('\n')
# 刪
class Del(object):
def del_(self,cardId):
readcard = ReadCard()
cards = readcard.read()
for card in cards:
# 刪除輸入的卡號
if cardId == card.cardId:
cards.remove(card)
break
else:
print("卡號不存在!")
return False
# 重新寫入文件
appendcard = AppendCard()
appendcard.append('',w='w')
for card in cards:
appendcard.append(card)
return True
4、person.py
'''
人
類名:Person
行為:開戶、查詢、取款、存儲、轉(zhuǎn)賬、改密、銷戶、退出
'''
class Person(object):
def __init__(self,name='',identity='',phoneNum='',card=None):
self.name = name
self.identity = identity
self.phoneNum = phoneNum
self.card = card
# 登錄
def login(self,atm):
card = atm.login()
if card:
self.card = card
return True
else:
return False
# 開戶
def newAccount(self,atm):
return atm.newAccount()
#找回密碼
def findBackPassword(self,atm):
return atm.findBackPassword()
# 查詢余額
def checkMoney(self, atm):
return atm.checkMoney(self.card)
# 存錢
def saveMoney(self, atm):
return atm.saveMoney(self.card)
# 取錢
def getMoney(self, atm):
return atm.getMoney(self.card)
# 轉(zhuǎn)賬
def transferMoney(self, atm):
return atm.transferMoney(self.card)
# 銷戶
def closeAccount(self, atm):
return atm.closeAccount(self.card)
# 掛失
def lockAccount(self, atm):
return atm.lockAccount()
# 解鎖
def unlockAccount(self, atm):
return atm.unlockAccount(self.card)
# 改密
def changePassword(self, atm):
return atm.changePassword(self.card)
# 退出系統(tǒng)
def exit(self, atm):
return atm.exit()
5、view.py
'''
管理員界面
類名:View
屬性:賬號,密碼
行為:管理員初始化界面 管理員登陸 系統(tǒng)功能界面 管理員注銷
系統(tǒng)功能:開戶 查詢 取款 存儲 轉(zhuǎn)賬 改密 銷戶 退出
'''
from check import Check
import time
class View(object):
def __init__(self,admin,password):
self.admin = admin
self.password = password
# 管理員初始化界面
def initface(self):
print("*------------------------------------*")
print("| |")
print("| 管理員界面正在啟動,請稍候... |")
print("| |")
print("*------------------------------------*")
time.sleep(1)
return
#管理員登錄界面
def login(self):
print("*------------------------------------*")
print("| |")
print("| 管理員登陸界面 |")
print("| |")
print("*------------------------------------*")
check = Check()
check.userName(self.admin,self.password)
print("*-------------登陸成功---------------*")
print(" 正在跳轉(zhuǎn)到系統(tǒng)功能界面,請稍候... ")
del check
time.sleep(1)
return
# 管理員注銷界面
def logout(self):
print("*------------------------------------*")
print("| |")
print("| 管理員注銷界面 |")
print("| |")
print("*------------------------------------*")
#確認(rèn)是否注銷
check = Check()
if not check.isSure('注銷'):
return False
check.userName(self.admin,self.password)
print("*-------------注銷成功---------------*")
print(" 正在關(guān)閉系統(tǒng),請稍候... ")
del check
time.sleep(1)
return True
#系統(tǒng)功能界面
'''
系統(tǒng)功能:開戶,查詢,取款,存儲,轉(zhuǎn)賬,銷戶,掛失,解鎖,改密,退出
'''
def funcInit(self):
print("*-------Welcome To Future Bank---------*")
print("| |")
print("| (1)開戶 (2)登錄 |")
print("| (3)找回密碼 (4)掛失 |")
print("| (T)退出 |")
print("| |")
print("*--------------------------------------*")
def funcInterface(self):
print("*-------Welcome To Future Bank---------*")
print("| |")
print("| (1)查詢 (5)改密 |")
print("| (2)存款 (6)解鎖 |")
print("| (3)取款 (7)銷戶 |")
print("| (4)轉(zhuǎn)賬 (T)退出 |")
print("| |")
print("*--------------------------------------*")
6、atm.py
'''
提款機:
類名:ATM
屬性:
行為(被動執(zhí)行操作):開戶,查詢,取款,存儲,轉(zhuǎn)賬,銷戶,掛失,解鎖,改密,退出
'''
from check import Check
from card import Card
from readAppendCard import ReadCard,AppendCard
import random
import time
class ATM(object):
def __init__(self):
# 實例化相關(guān)的類
self.check = Check()
self.readCard = ReadCard()
self.appendCard = AppendCard()
self.cards = self.readCard.read()
# 顯示功能界面
def funcShow(self,ope):
if ope != "找回密碼":
print("*-------Welcome To Future Bank-------*")
print("| %s功能界面 |"%ope)
print("*------------------------------------*")
else:
# 顯示找回密碼界面
print("*-------Welcome To Future Bank-------*")
print("| 找回密碼功能界面 |")
print("*------------------------------------*")
# 卡號輸入
def cardInput(self,ope=''):
while True:
cardId = input("請輸入卡號:")
password = input("請輸入密碼:")
card = self.check.isCardAndPasswordSure(self.cards, cardId,password)
if not card:
print("卡號或密碼輸入有誤!!!")
if ope == 'login' or ope == 'lock':
return False
else:
continue
else:
return card
# 登錄
def login(self):
self.funcShow("登錄")
return self.cardInput('login')
#找回密碼
def findBackPassword(self):
self.funcShow("找回密碼")
cardId = input("請輸入卡號:")
card = self.check.isCardIdExist(self.cards,cardId)
if card:
if not self.check.isCardInfoSure(card,"找回密碼"):
return
newpassword = self.check.newPasswordInput()
index = self.cards.index(card)
self.cards[index].password = newpassword
self.writeCard()
print("找回密碼成功!請重新登錄!!!")
time.sleep(1)
return True
else:
print("卡號不存在!!!")
return True
# 開戶
def newAccount(self):
self.funcShow("開戶")
# 輸入身份證號和手機號
pnum = self.check.phoneInput()
iden = self.check.identifyInput()
print("正在執(zhí)行開戶程序,請稍候...")
while True:
# 隨機生成6位卡號
cardId = str(random.randrange(100000, 1000000))
# 隨機生成的卡號存在就繼續(xù)
if self.check.isCardIdExist(self.cards,cardId):
continue
else:
break
# 初始化卡號密碼,卡里的錢,卡的鎖定狀態(tài)
card = Card(cardId, '888888', 0, iden, pnum , 'False')
self.appendCard.append(card)
print("開戶成功,您的卡號為%s,密碼為%s,卡余額為%d元!"%(cardId,'888888',0))
print("為了賬戶安全,請及時修改密碼!!!")
# 更新卡號列表
self.cards = self.readCard.read()
return True
# 查詢
def checkMoney(self,card):
self.funcShow("查詢")
if self.check.isCardLock(card):
print("查詢失敗!")
else:
print("卡上余額為%d元!" %card.money)
time.sleep(1)
# 存款
def saveMoney(self,card):
self.funcShow("存款")
if self.check.isCardLock(card):
print("存錢失敗!")
else:
mon = self.check.moneyInput("存款")
# 找到所有卡中對應(yīng)的卡號,然后對此卡進行存款操作
index = self.cards.index(card)
self.cards[index].money += mon
print("正在執(zhí)行存款程序,請稍候...")
time.sleep(1)
self.writeCard()
print("存款成功!卡上余額為%d元!"%self.cards[index].money)
time.sleep(1)
# 取款
def getMoney(self,card):
self.funcShow("取款")
if self.check.isCardLock(card):
print("取錢失??!")
else:
print("卡上余額為%d元!" %card.money)
mon = self.check.moneyInput("取款")
if mon:
if mon > card.money:
print("余額不足,您當(dāng)前余額為%d元!"%card.money)
time.sleep(1)
else:
print("正在執(zhí)行取款程序,請稍候...")
time.sleep(1)
# 找到所有卡中對應(yīng)的卡號,然后對此卡進行存款操作
index = self.cards.index(card)
self.cards[index].money -= mon
self.writeCard()
print("取款成功!卡上的余額為%d元!"%self.cards[index].money)
time.sleep(1)
# 轉(zhuǎn)賬
def transferMoney(self,card):
self.funcShow("轉(zhuǎn)賬")
if self.check.isCardLock(card): #如果卡已鎖定就不能進行轉(zhuǎn)賬操作
print("轉(zhuǎn)賬失敗!")
return
while True:
cardId = input("請輸入對方的賬號:")
if cardId == card.cardId:
print("不能給自己轉(zhuǎn)賬!!!")
return
cardOther = self.check.isCardIdExist(self.cards,cardId) #判斷對方卡號是否存在
if cardOther == False:
print("對方賬號不存在!!!")
return
else:
break
while True:
print("卡上余額為%d元"%card.money)
mon = self.check.moneyInput("轉(zhuǎn)賬")
if not mon: #輸入的金額不對就返回
return
if mon > card.money: #輸入的金額大于卡上余額就返回
print("余額不足,卡上余額為%d元!" % card.money)
return
else:
break
print("正在執(zhí)行轉(zhuǎn)賬程序,請稍候...")
time.sleep(1)
index = self.cards.index(card) # 找到所有卡中對應(yīng)的卡號,然后對此卡進行轉(zhuǎn)賬操作
self.cards[index].money -= mon
indexOther = self.cards.index(cardOther) #找到對卡卡號所處位置
self.cards[indexOther].money += mon
self.writeCard()
print("轉(zhuǎn)賬成功!卡上余額為%d元!" % self.cards[index].money)
time.sleep(1)
# 銷戶
def closeAccount(self,card):
self.funcShow("銷戶")
if not self.check.isCardInfoSure(card,"銷戶"):
return
if card.money >0:
print("卡上還有余額,不能進行銷戶!!!")
return
if self.check.isSure("銷戶"):
self.cards.remove(card) #移除當(dāng)前卡號
self.writeCard()
print("銷戶成功!")
time.sleep(1)
return True
# 掛失
def lockAccount(self):
self.funcShow("掛失")
card = self.cardInput('lock')
if not card:
return
if card.cardLock == "True":
print("卡已處于鎖定狀態(tài)!!!")
return
if not self.check.isCardInfoSure(card,"掛失"):
return
if self.check.isSure("掛失"):
index = self.cards.index(card) #找到所有卡中對應(yīng)的卡號,然后對此卡進行掛失操作
self.cards[index].cardLock = "True"
self.writeCard()
print("掛失成功!")
time.sleep(1)
return True
# 解鎖
def unlockAccount(self,card):
self.funcShow("解鎖")
if card.cardLock == 'False':
print("無需解鎖,卡處于正常狀態(tài)!!!")
return
if not self.check.isCardInfoSure(card,"解鎖"):
return
index = self.cards.index(card)
self.cards[index].cardLock = "False"
self.writeCard()
print("解鎖成功!")
time.sleep(1)
return True
# 改密
def changePassword(self,card):
self.funcShow("改密")
if self.check.isCardLock(card):
print("卡處于鎖定狀態(tài),不能進行改密!!!")
return
if not self.check.isCardInfoSure(card,"改密"):
return
# 輸入舊密碼
while True:
password = input("請輸入舊密碼:")
if self.check.isPasswordSure(password,card.password):
break
else:
print("卡號原密碼輸入錯誤!")
return
newpassword = self.check.newPasswordInput()
index = self.cards.index(card) #找到所有卡中對應(yīng)的卡號,然后對此卡進行改密操作
self.cards[index].password = newpassword
self.writeCard()
print("改密成功!請重新登錄!!!")
time.sleep(1)
return True
# 寫入文件
def writeCard(self):
self.appendCard.append('', w='w') #先清除原文件再重新寫入
for card in self.cards:
self.appendCard.append(card)
# 退出
def exit(self):
if self.check.isSure("退出"):
return True
else:
return False
7、check.py
'''
驗證類:
用戶名、密碼、卡號、身份證、手機號驗證
使用正則表達式進行文本搜索
'''
import re
class Check(object):
def __init__(self):
pass
#用戶驗證
def userName(self,admin,password):
self.admin = admin
self.password = password
while True:
admin = input("請輸入用戶名:")
password = input("請輸入密碼:")
if admin != self.admin or password != self.password:
print("用戶名或密碼輸入有誤,請重新輸入!!!")
continue
else:
return
#是否確認(rèn)某操作
def isSure(self,operate):
while True:
res = input("是否確認(rèn)%s?【yes/no】"%operate)
if res not in ['yes','no']:
print("輸入有誤,請重新輸入!!!")
continue
elif res == 'yes':
return True
else:
return False
# 手機號驗證
def phoneInput(self):
# 簡單的手機號驗證:開頭為1且全部為數(shù)字,長度為11位
while True:
pnum = input("請輸入您的手機號:")
res = re.match(r"^1\d{10}$",pnum)
if not res:
print("手機號輸入有誤,請重新輸入!!!")
continue
return pnum
# 身份證號驗證
def identifyInput(self):
# 簡單的身份證號驗證:6位,只有最后一可以為x,其余必須為數(shù)字
while True:
iden = input("請輸入您的身份證號(6位數(shù)字):")
res = re.match(r"\d{5}\d|x$",iden)
if not res:
print("身份證號輸入有誤,請重新輸入!!!")
continue
return iden
# 卡號是否存在
def isCardIdExist(self,cards,cardId):
for card in cards:
if cardId == card.cardId:
return card
else:
return False
# 卡號和密碼是否一致
def isCardAndPasswordSure(self,cards,cardId,password):
card = self.isCardIdExist(cards,cardId)
if card:
if card.password == password:
return card
return False
# 密碼二次確認(rèn)是否正確
def isPasswordSure(self, newassword,oldpassword):
if newassword == oldpassword:
return True
else:
return False
# 卡號完整信息驗證
def isCardInfoSure(self,card,ope):
phoneNum = input("請輸入手機號:")
iden = input("請輸入身份證號:")
if card.phoneNum == phoneNum and card.identityId == iden:
return True
print("%s失敗!!!\n密碼、手機號或身份證號與卡中綁定的信息不一致!!!"%ope)
return False
# 卡號是否鎖定
def isCardLock(self,card):
if card.cardLock == "True":
print("此卡已掛失!")
return True
return False
# 輸入金額驗證
def moneyInput(self,ope):
mon = input("輸入%s金額(100的倍數(shù)):"%ope)
# 輸入的錢必須是100的倍數(shù)
if re.match(r"[123456789]\d*[0]{2}$", mon):
return int(mon)
print("輸入有誤,%s金額必須是100的倍數(shù)!請重新輸入!!!"%ope)
return False
def newPasswordInput(self):
while True:
newpassword = input("請輸入新密碼:")
if not re.match(r"\d{6}$",newpassword):
print("密碼必須是6位的純數(shù)字!!!")
continue
newpasswordAgain = input("請重復(fù)輸入新密碼:")
if self.isPasswordSure(newpassword, newpasswordAgain):
break
else:
print("兩次輸入不一致!")
continue
return newpassword
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python+Tkinter簡單實現(xiàn)注冊登錄功能
這篇文章主要為大家詳細(xì)介紹了Python+Tkinter簡單實現(xiàn)注冊登錄功能,連接本地MySQL數(shù)據(jù)庫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
Python實現(xiàn)斐波那契數(shù)列的多種寫法總結(jié)
這篇文章主要給大家介紹了利用Python實現(xiàn)斐波那契數(shù)列的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
基于python利用Pyecharts使高清圖片導(dǎo)出并在PPT中動態(tài)展示
這篇文章主要介紹了基于python利用Pyecharts使高清圖片導(dǎo)出并在PPT中動態(tài)展示,pyecharts?是一個用于生成?Echarts?圖表的類庫。Echarts?是百度開源的一個數(shù)據(jù)可視化?JS?庫,下面來看看具體的實現(xiàn)過程吧,需要的小伙伴也可以參考一下2022-01-01
Elasticsearch映射字段數(shù)據(jù)類型及管理
這篇文章主要介紹了Elasticsearch映射字段數(shù)據(jù)類型及管理的講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
python strip() 函數(shù)和 split() 函數(shù)的詳解及實例
這篇文章主要介紹了 python strip() 函數(shù)和 split() 函數(shù)的詳解及實例的相關(guān)資料,需要的朋友可以參考下2017-02-02
Micropython固件使用Pico刷固件并配置VsCode開發(fā)環(huán)境的方法
這篇文章主要介紹了Micropython固件使用Pico刷固件并配置VsCode開發(fā)環(huán)境的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-07-07
Python numpy 數(shù)組的向量化運算操作方法
這篇文章主要介紹了Python numpy數(shù)組的向量化運算操作方法,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06

