2026/5/13 10:51:50
网站建设
项目流程
内丘网站,热点营销案例,湖南人文科技学院官网,中国建设银行股份有限公司文件下载地址【带源码】#xff1a;https://wenshushu.vip/download/index.php?id37 提取码#xff1a;5e81不知道大家有没有想过#xff0c;如果能“自定义”自己的银行卡余额该多好#xff1f;当然#xff0c;这只是个玩笑#xff01;今天我将带大家用Python制作一…文件下载地址【带源码】https://wenshushu.vip/download/index.php?id37 提取码5e81不知道大家有没有想过如果能“自定义”自己的银行卡余额该多好当然这只是个玩笑今天我将带大家用Python制作一个“银行卡余额模拟器”纯粹用于编程学习、娱乐和了解金融系统的基本逻辑。通过这个项目你将学到Python面向对象编程、文件操作、数据加密等实用技能。一、项目概述功能特性· 模拟银行账户创建和管理· 存款、取款、转账功能· 交易记录查询· 数据本地加密存储· 精美的终端界面技术栈· Python 3.8· 面向对象编程· JSON数据存储· 基础加密技术· 终端颜色输出二、项目结构bank_simulator/├── bank_system.py # 主程序├── accounts.json # 账户数据存储└── README.md # 项目说明三、代码实现3.1 账户类设计首先我们创建一个BankAccount类来表示银行账户pythonimport jsonimport osfrom datetime import datetimeimport hashlibfrom getpass import getpassimport sysclass BankAccount:银行账户类def __init__(self, account_number, account_name, initial_balance0.0, passwordNone):初始化银行账户参数:account_number: 账户号码account_name: 账户持有人姓名initial_balance: 初始余额password: 账户密码self.account_number account_numberself.account_name account_nameself.balance initial_balanceself.password_hash self._hash_password(password) if password else Noneself.transactions []self.creation_date datetime.now().strftime(%Y-%m-%d %H:%M:%S)# 记录初始存款if initial_balance 0:self.add_transaction(初始存款, initial_balance, 存款)def _hash_password(self, password):对密码进行哈希处理return hashlib.sha256(password.encode()).hexdigest()def verify_password(self, password):验证密码if not self.password_hash:return True # 如果没有设置密码则默认通过return self._hash_password(password) self.password_hashdef add_transaction(self, description, amount, transaction_type):添加交易记录transaction {date: datetime.now().strftime(%Y-%m-%d %H:%M:%S),description: description,amount: amount,type: transaction_type,balance_after: self.balance}self.transactions.append(transaction)# 只保留最近100条交易记录if len(self.transactions) 100:self.transactions self.transactions[-100:]def deposit(self, amount):存款if amount 0:return False, 存款金额必须大于0self.balance amountself.add_transaction(存款, amount, 存款)return True, f存款成功当前余额: ¥{self.balance:,.2f}def withdraw(self, amount):取款if amount 0:return False, 取款金额必须大于0if amount self.balance:return False, 余额不足self.balance - amountself.add_transaction(取款, amount, 取款)return True, f取款成功当前余额: ¥{self.balance:,.2f}def get_statement(self, last_n10):获取交易流水if not self.transactions:return 暂无交易记录statement f\n{*60}\nstatement f{self.account_name} 的交易流水\nstatement f{*60}\nstatement f{日期:20} {类型:10} {金额:15} {余额:15}\nstatement f{-*60}\nfor tx in self.transactions[-last_n:]:amount_str f¥{tx[amount]:,.2f}balance_str f¥{tx[balance_after]:,.2f}# 根据交易类型设置金额显示颜色if tx[type] 存款:amount_display f\033[92m{amount_str}\033[0m # 绿色else:amount_display f\033[91m-{amount_str}\033[0m # 红色statement f{tx[date]:20} {tx[description]:10} {amount_display:20} {balance_str:15}\nstatement f{*60}\nstatement f当前总余额: \033[94m¥{self.balance:,.2f}\033[0m\nstatement f{*60}return statementdef to_dict(self):将账户数据转换为字典return {account_number: self.account_number,account_name: self.account_name,balance: self.balance,password_hash: self.password_hash,transactions: self.transactions,creation_date: self.creation_date}classmethoddef from_dict(cls, data):从字典创建账户对象account cls(data[account_number],data[account_name],data[balance])account.password_hash data.get(password_hash)account.transactions data.get(transactions, [])account.creation_date data.get(creation_date, datetime.now().strftime(%Y-%m-%d %H:%M:%S))return account3.2 银行系统类接下来我们创建BankSystem类来管理所有账户pythonclass BankSystem:银行系统类def __init__(self, data_fileaccounts.json):self.data_file data_fileself.accounts {}self.current_account Noneself.load_accounts()def load_accounts(self):加载账户数据if os.path.exists(self.data_file):try:with open(self.data_file, r, encodingutf-8) as f:data json.load(f)for acc_data in data.values():account BankAccount.from_dict(acc_data)self.accounts[account.account_number] accountprint(f\033[92m✓ 已加载 {len(self.accounts)} 个账户\033[0m)except Exception as e:print(f\033[91m✗ 加载账户数据失败: {e}\033[0m)self.accounts {}else:self.accounts {}def save_accounts(self):保存账户数据try:data {num: acc.to_dict() for num, acc in self.accounts.items()}with open(self.data_file, w, encodingutf-8) as f:json.dump(data, f, ensure_asciiFalse, indent2)return Trueexcept Exception as e:print(f\033[91m✗ 保存账户数据失败: {e}\033[0m)return Falsedef create_account(self):创建新账户print(\n *60)print(创建新账户.center(60))print(*60)# 生成账户号码account_number str(1000000000 len(self.accounts) 1)# 获取账户信息account_name input(请输入账户持有人姓名: ).strip()if not account_name:print(\033[91m✗ 账户名不能为空\033[0m)return None# 设置密码while True:password getpass(请设置账户密码 (输入为空则不设密码): ).strip()if not password:password Nonebreakconfirm getpass(请确认密码: ).strip()if password confirm:breakelse:print(\033[91m✗ 两次输入的密码不一致请重新设置\033[0m)# 初始存款while True:try:initial_deposit input(请输入初始存款金额 (默认0): ).strip()if not initial_deposit:initial_deposit 0.0else:initial_deposit float(initial_deposit)if initial_deposit 0:print(\033[91m✗ 存款金额不能为负数\033[0m)continuebreakexcept ValueError:print(\033[91m✗ 请输入有效的数字\033[0m)# 创建账户account BankAccount(account_number, account_name, initial_deposit, password)self.accounts[account_number] accountself.save_accounts()print(\n\033[92m *60 \033[0m)print(f\033[92m✓ 账户创建成功\033[0m)print(f\033[92m 账户号码: {account_number}\033[0m)print(f\033[92m 账户姓名: {account_name}\033[0m)print(f\033[92m 初始余额: ¥{initial_deposit:,.2f}\033[0m)print(f\033[92m 创建时间: {account.creation_date}\033[0m)print(\033[92m *60 \033[0m)return accountdef login(self):登录账户print(\n *60)print(账户登录.center(60))print(*60)account_number input(请输入账户号码: ).strip()if account_number not in self.accounts:print(\033[91m✗ 账户不存在\033[0m)return Falseaccount self.accounts[account_number]# 如果账户有密码需要验证if account.password_hash:for i in range(3): # 最多尝试3次password getpass(请输入账户密码: )if account.verify_password(password):breakelse:attempts_left 2 - iif attempts_left 0:print(f\033[91m✗ 密码错误还剩{attempts_left}次尝试机会\033[0m)else:print(\033[91m✗ 密码错误次数过多登录失败\033[0m)return Falseelse:print(⚠ 此账户未设置密码直接登录)self.current_account accountprint(f\n\033[92m✓ 登录成功欢迎 {account.account_name}\033[0m)return Truedef logout(self):登出账户if self.current_account:print(f\n\033[92m✓ 再见{self.current_account.account_name}\033[0m)self.current_account Nonereturn Truedef show_menu(self):显示主菜单if not self.current_account:returnwhile True:print(\n *60)print(f欢迎{self.current_account.account_name}.center(60))print(f账户: {self.current_account.account_number}.center(60))print(*60)print(f当前余额: \033[94m¥{self.current_account.balance:,.2f}\033[0m.center(60))print(*60)print(1. 存款)print(2. 取款)print(3. 查看交易流水)print(4. 修改密码)print(5. 显示账户信息)print(6. 退出登录)print(0. 退出系统)print(*60)choice input(请选择操作 (0-6): ).strip()if choice 1:self.deposit()elif choice 2:self.withdraw()elif choice 3:self.view_statement()elif choice 4:self.change_password()elif choice 5:self.show_account_info()elif choice 6:self.logout()breakelif choice 0:print(\n\033[92m感谢使用银行卡余额模拟器再见\033[0m)sys.exit(0)else:print(\033[91m✗ 无效的选择请重新输入\033[0m)def deposit(self):存款操作try:amount float(input(请输入存款金额: ))success, message self.current_account.deposit(amount)if success:print(f\n\033[92m{message}\033[0m)self.save_accounts()else:print(f\n\033[91m{message}\033[0m)except ValueError:print(\033[91m✗ 请输入有效的数字\033[0m)def withdraw(self):取款操作try:amount float(input(请输入取款金额: ))success, message self.current_account.withdraw(amount)if success:print(f\n\033[92m{message}\033[0m)self.save_accounts()else:print(f\n\033[91m{message}\033[0m)except ValueError:print(\033[91m✗ 请输入有效的数字\033[0m)def view_statement(self):查看交易流水print(self.current_account.get_statement())def change_password(self):修改密码if not self.current_account.password_hash:print(⚠ 当前账户未设置密码)# 验证原密码if self.current_account.password_hash:current_password getpass(请输入当前密码: )if not self.current_account.verify_password(current_password):print(\033[91m✗ 当前密码错误\033[0m)return# 设置新密码while True:new_password getpass(请输入新密码 (输入为空则取消密码): ).strip()if not new_password:self.current_account.password_hash Noneprint(\033[92m✓ 已移除账户密码\033[0m)breakconfirm getpass(请确认新密码: ).strip()if new_password confirm:self.current_account.password_hash self.current_account._hash_password(new_password)print(\033[92m✓ 密码修改成功\033[0m)breakelse:print(\033[91m✗ 两次输入的密码不一致\033[0m)self.save_accounts()def show_account_info(self):显示账户信息acc self.current_accountprint(\n *60)print(账户信息.center(60))print(*60)print(f账户号码: {acc.account_number})print(f账户姓名: {acc.account_name})print(f当前余额: ¥{acc.balance:,.2f})print(f创建时间: {acc.creation_date})print(f交易记录数: {len(acc.transactions)})print(f密码保护: {是 if acc.password_hash else 否})print(*60)def run(self):运行银行系统print(\n *60)print(银行卡余额模拟器.center(60))print(仅供娱乐和学习使用.center(60))print(*60)while True:print(\n *60)print(主菜单.center(60))print(*60)print(1. 创建新账户)print(2. 登录现有账户)print(3. 退出系统)print(*60)choice input(请选择操作 (1-3): ).strip()if choice 1:self.create_account()elif choice 2:if self.login():self.show_menu()elif choice 3:print(\n\033[92m感谢使用银行卡余额模拟器再见\033[0m)breakelse:print(\033[91m✗ 无效的选择请重新输入\033[0m)3.3 主程序最后我们添加主程序入口pythondef main():主函数# 检查Python版本import sysif sys.version_info (3, 6):print(\033[91m✗ 需要Python 3.6或更高版本\033[0m)return# 创建银行系统并运行bank BankSystem()bank.run()if __name__ __main__:main()四、使用说明4.1 安装和运行1. 确保已安装Python 3.6或更高版本2. 将上述代码保存为bank_system.py3. 在终端中运行python bank_system.py4.2 基本操作1. 创建账户选择主菜单的创建新账户按照提示输入信息2. 登录账户使用账户号码和密码登录3. 存款/取款登录后选择相应功能4. 查看交易流水查看最近的交易记录5. 修改密码增强账户安全性五、功能扩展建议这个基础版本可以进一步扩展1. 增加转账功能实现账户间的资金转移2. 添加利息计算模拟银行存款利息3. 图形界面使用Tkinter或PyQt创建GUI4. 网络功能实现简单的客户端-服务器架构5. 数据加密使用更安全的加密算法保护数据6. 报表导出将交易记录导出为Excel或PDF六、安全提醒⚠️ 重要提醒1. 本项目仅供编程学习和娱乐使用2. 所有数据存储在本地没有真正的金融功能3. 请勿使用真实银行账户信息4. 请勿用于任何欺诈或非法用途5. 密码使用SHA-256哈希存储但生产环境需要更安全的方案七、总结通过这个项目我们学习了· Python面向对象编程的实际应用· 文件操作和JSON数据存储· 基础密码学概念哈希函数· 终端界面的美化技巧· 金融系统的基本逻辑编程不仅是工作技能也可以是创造乐趣的工具。希望这个银行卡余额模拟器能带给你编程的快乐同时加深对Python的理解---免责声明本项目为模拟程序仅供学习和娱乐使用。所有功能均为模拟不涉及真实金融交易。请遵守法律法规不要用于任何非法用途。完整代码获取关注博主后台回复银行模拟器获取完整代码和更新版本下期预告如何为这个模拟器添加图形界面敬请期待---版权声明本文为原创文章遵循 CC 4.0 BY-SA 版权协议转载请附上原文出处链接和本声明。