优客文库提供全面的范文格式和文档模板,包括申请书、合同、借据、证明、求职信等,助力您快速撰写专业文档。

试用面向对象方法,设计本书习题2第二题中描述的储蓄系统

来自 河北省邯郸市 的网友 时间: 热度:°C 加入收藏 我要投稿 点赞()
为了设计一个面向对象的储蓄系统,首先需要确定系统中的主要对象及其属性和行为。根据习题2的描述,我们可以考虑以下几个类:

1. account(账户):代表储蓄账户的类,具有余额(balance)属性和存款(deposit)、取款(withdraw)等方法。

2. customer(客户):代表客户的类,拥有姓名(name)、身份证号(id)属性,以及创建账户(openaccount)的行为。

3. bank(银行):代表银行的类,管理着多个账户,可以有添加客户(addcustomer)、添加账户(addaccount)等方法。

下面是这些类的简单实现,使用python语言作为示例:

```python
class account:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance

def deposit(self, amount):
self.balance += amount

def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("insufficient funds")

def get_balance(self):
return self.balance


class customer:
def __init__(self, name, id):
self.name = name
self.id = id
self.accounts = []

def open_account(self):
new_account = account(len(self.accounts))
self.accounts.append(new_account)
return new_account.account_number


class bank:
def __init__(self):
self.customers = []

def add_customer(self, customer):
self.customers.append(customer)

def get_customer(self, id):
for customer in self.customers:
if customer.id == id:
return customer
return None

def add_account_to_customer(self, id, account_number):
customer = self.get_customer(id)
if customer is not none:
account = account(account_number)
customer.accounts.append(account)
return account_number
return none
```

在这段代码中,`account` 类用于处理与账户相关的操作,如存款、取款和查询余额。`customer` 类代表客户,可以开设新账户。`bank` 类代表银行,可以添加客户和账户。

要使用这个储蓄系统,你可以创建一个`bank`实例,然后添加`customer`实例到这个银行。每个客户可以通过调用`open_account`方法来创建新的`account`实例。以下是如何使用这些类的简单示例:

```python
# 创建银行实例
mybank = bank()

# 创建客户实例并添加到银行
customer1 = customer("alice", "123456")
mybank.add_customer(customer1)

# 客户开设账户
account_number = customer1.open_account()

# 通过银行为该客户添加账户
account_number = mybank.add_account_to_customer(customer1.id, len(customer1.accounts))

# 存钱和取钱操作
customer1.accounts[0].deposit(1000)
print(customer1.accounts[0].get_balance()) # 应该输出1000
customer1.accounts[0].withdraw(500)
print(customer1.accounts[0].get_balance()) # 应该输出500
```

请注意,这仅仅是一个基本实现。在真实的应用程序中,你可能需要更多的功能,如事务处理、多币种支持、利率计算、安全性检查、异常处理等。此外,你可能还需要将数据持久化到数据库中,而不是仅存储在内存中。
221381
领取福利

微信扫码领取福利

微信扫码分享