酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Python实现BankAccount类:含构造、属性封装与静态成员,附主函数测试

以下是使用 Python 实现的 `BankAccount` 类: ```python import random class BankAccount: totalAccounts = 0 # 静态字段,统计账户总数 def __init__(self, accountNumber=None, ownerName=None, balance=0): if accountNumber is None: self.accountNumber = f"ACC-{random.randint(1, 999):03}" # 生成随机账号 else: self.accountNumber = accountNumber if ownerName is None: self.ownerName = "Anonymous" else: self.ownerName = ownerName self._balance = balance # 私有属性表示余额 BankAccount.totalAccounts += 1 # 增加账户总数 @property # Balance 属性为只读 def balance(self): return self._balance def deposit(self, amount): """ 存款方法 :param amount: 存款金额 """ self._balance += amount def withdraw(self, amount): """ 取款方法 :param amount: 取款金额 :return: 取款成功返回 True,余额不足返回 False """ if self._balance >= amount: self._balance -= amount return True else: return False @staticmethod def getTotalAccounts(): """ 静态方法,返回账户总数 :return: 账户总数 """ return BankAccount.totalAccounts # 主函数测试 if __name__ == "__main__": account1 = BankAccount("ACC-001", "Alice", 1000) account2 = BankAccount() print(f"账户 1 的余额: {account1.balance}") account1.deposit(500) print(f"存款 500 后账户 1 的余额: {account1.balance}") if account1.withdraw(800): print("取款 800 成功") else: print("余额不足,取款失败") print(f"账户总数: {BankAccount.getTotalAccounts()}") ``` 额外需要注意的逻辑点: 1. 对于随机账号的生成,可以考虑增加更多的随机性或规则。 2. 取款和存款的操作,要确保对异常情况的处理完善,比如输入负数金额等。 3. 考虑添加日志记录功能,以便跟踪账户的操作历史。 ######[AI写代码神器 | 564点数解答 | 2025-04-13 15:48:56]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]