酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

设计一个BankAccount类,要求: 1.‌构造函数‌ 包含有参构造函数,初始化账号(AccountNumber)、户名(OwnerName)和初始余额(Balance)。 无参构造函数默认生成一个随机账号(如ACC-001),户名为"Anonymous",余额为0。 ‌ 2.属性与封装‌ Balance属性为只读,仅能通过类内方法修改。 提供Deposit(存款)和Withdraw(取款)方法,取款时需验证余额是否充足。 3.‌静态成员‌ 静态字段totalAccounts统计所有账户总数。 静态方法GetTotalAccounts返回当前总账户数。 并在主函数测试

以下是使用 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. 考虑添加日志记录功能,以便跟踪账户的操作历史。 [2025-04-13 15:48:56 | AI写代码神器 | 564点数解答]

相关提问