用python的类做一个存、取款功能
时间: 2023-06-05 22:04:52 浏览: 46
好的,我可以帮您解答关于用 Python 类实现存取款功能的问题。您可以定义一个名为 BankAccount 的类,该类包含以下方法:存款 deposit()、取款 withdraw()、查询余额 get_balance()。
示例代码如下:
```
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"成功存入 {amount} 元,当前余额为 {self.balance} 元。")
def withdraw(self, amount):
if self.balance - amount >= 0:
self.balance -= amount
print(f"成功取出 {amount} 元,当前余额为 {self.balance} 元。")
else:
print("余额不足,无法取款。")
def get_balance(self):
print(f"当前余额为 {self.balance} 元。")
# 创建一个账户,并初始化余额为 1000 元
account = BankAccount(1000)
# 存款 200 元
account.deposit(200)
# 取款 500 元
account.withdraw(500)
# 查询余额
account.get_balance()
```
希望这个代码片段能够帮助您。如果您还有其他问题,请继续提出。