1. 银行账户开户与基本信息管理
任务说明
本案例实现一个最小可运行的银行账户开户模块:录入客户信息、选择账户类型、生成唯一账号,并将账户初始状态设为 ACTIVE。核心数据保存在内存中,便于直接验证开户流程。
环境与依赖
- Python 3.8+,仅使用标准库(
dataclasses、uuid、datetime)。 - 无需第三方依赖,直接运行脚本即可。
开户流程
完整实现
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4
from enum import Enum
class AccountType(Enum):
SAVINGS = "储蓄账户"
CHECKING = "活期账户"
FIXED = "定期账户"
class AccountStatus(Enum):
ACTIVE = "ACTIVE"
FROZEN = "FROZEN"
CLOSED = "CLOSED"
@dataclass
class Customer:
name: str
id_card: str
phone: str
@dataclass
class Account:
account_no: str
customer: Customer
account_type: AccountType
status: AccountStatus
balance: float = 0.0
created_at: str = field(default_factory=lambda: datetime.now().isoformat(timespec="seconds"))
class AccountStore:
def __init__(self):
self._accounts = {}
def _generate_account_no(self) -> str:
# 16位数字账号,前缀62表示银行标识
return "62" + uuid4().hex[:14].translate(str.maketrans("abcdef", "012345"))
def open_account(self, customer: Customer, account_type: AccountType) -> Account:
if not customer.name or not customer.id_card:
raise ValueError("客户姓名与身份证号不能为空")
if not isinstance(account_type, AccountType):
raise ValueError("账户类型无效")
account_no = self._generate_account_no()
while account_no in self._accounts:
account_no = self._generate_account_no()
account = Account(
account_no=account_no,
customer=customer,
account_type=account_type,
status=AccountStatus.ACTIVE,
)
self._accounts[account_no] = account
return account
def get(self, account_no: str) -> Account:
return self._accounts.get(account_no)
if __name__ == "__main__":
store = AccountStore()
customer = Customer(name="张三", id_card="110101199001011234", phone="13800000000")
account = store.open_account(customer, AccountType.SAVINGS)
print("账号:", account.account_no)
print("户名:", account.customer.name)
print("类型:", account.account_type.value)
print("状态:", account.status.value)
print("余额:", account.balance)
print("开户时间:", account.created_at)
# 验证:账号可被查询到,且状态为 ACTIVE
fetched = store.get(account.account_no)
assert fetched is not None
assert fetched.status == AccountStatus.ACTIVE
assert len(account.account_no) == 16 and account.account_no.isdigit()
print("验证通过:账户已开户并处于 ACTIVE 状态")
运行方式
python account_open.py
验证方法与通过条件
- 脚本正常退出且打印“验证通过:账户已开户并处于 ACTIVE 状态”。
- 账号为 16 位纯数字,且能通过
store.get()查询到同一账户对象。 - 账户初始
status为ACTIVE,balance为 0.0。 - 若客户姓名或身份证号为空,
open_account抛出ValueError,可用于补充异常路径测试。