说明
《Python 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)Python 实现一个简单的银行账户类 BankAccount,包含初始化方法、存款、取款、获取余额等功能。
Python 类 BankAccount,用于模拟银行账户的基本功能。该类应包含以下方法:
初始化方法:
将指定金额存入账户。
取款方法 withdraw(amount: float) -> None
:
从账户中取出指定金额。
获取余额方法 get_balance() -> float
:返回当前账户的余额。
示例用法:创建一个银行账户实例,进行一系列存款、取款和获取余额的操作,并在每次操作后打印相关信息。
Python 代码如下
class BankAccount:
def __init__(self, account_holder, balance=0.0):
"""
Initialize a BankAccount.
Args:
- account_holder (str): The name of the account holder.
- balance (float): Initial balance. Default is 0.0.
"""
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
"""
Deposit money into the account.
Args:
- amount (float): The amount to be deposited.
Returns:
- None
"""
if amount > 0:
self.balance += amount
print(f"Deposit of ${amount:.2f} successful. New balance: ${self.balance:.2f}")
else:
print("Invalid deposit amount. Please enter a positive value.")
def withdraw(self, amount):
"""
Withdraw money from the account.
Args:
- amount (float): The amount to be withdrawn.
Returns:
- None
"""
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrawal of ${amount:.2f} successful. New balance: ${self.balance:.2f}")
elif amount > self.balance:
print("Insufficient funds. Withdrawal canceled.")
else:
print("Invalid withdrawal amount. Please enter a positive value.")
def get_balance(self):
"""
Get the current balance of the account.
Returns:
- float: The current balance.
"""
return self.balance
# Example usage:
account1 = BankAccount(account_holder="Alice", balance=1000.0)
account1.deposit(500.0)
account1.withdraw(200.0)
account1.deposit(100.0)
print(f"Current balance for {account1.account_holder}: ${account1.get_balance():.2f}")
'''
Deposit of $500.00 successful. New balance: $1500.00
Withdrawal of $200.00 successful. New balance: $1300.00
Deposit of $100.00 successful. New balance: $1400.00
Current balance for Alice: $1400.00
'''
查看相关链接中的知识。
(完)
更新时间:2024-08-16 22:50:40 标签:python 习题 类 余额