Python 创建一个类来模拟银行账户,支持存款、取款、查询余额等操作
我们将创建一个名为 BankAccount
的类,用于模拟银行账户的基本操作。这个类将包含存款、取款和查询余额的功能。我们将使用实例变量来存储账户余额,并提供方法来操作这些变量。
实例
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
elif amount <= 0:
print("Withdrawal amount must be positive.")
else:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}.")
def get_balance(self):
return self.balance
# 示例使用
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Current balance: {account.get_balance()}")
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
elif amount <= 0:
print("Withdrawal amount must be positive.")
else:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}.")
def get_balance(self):
return self.balance
# 示例使用
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Current balance: {account.get_balance()}")
代码解析:
__init__
方法是类的构造函数,用于初始化账户所有者和余额。owner
是账户所有者的名字,balance
是账户的初始余额,默认为 0。deposit
方法用于存款。它接受一个金额参数,如果金额为正数,则将其加到余额中,并打印新的余额。如果金额为负数或零,则打印错误信息。withdraw
方法用于取款。它检查取款金额是否大于余额,如果是,则打印资金不足的信息。如果金额为正数且不超过余额,则从余额中减去该金额,并打印新的余额。get_balance
方法返回当前账户的余额。
输出结果:
Deposited 50. New balance is 150. Withdrew 20. New balance is 130. Current balance: 130
点我分享笔记