Python 实现一个银行账户类,支持存款和取款

Document 对象参考手册 Python3 实例

我们将创建一个简单的银行账户类,这个类将包含账户的基本信息,如账户名和余额,并且支持存款和取款操作。

实例

class BankAccount:
    def __init__(self, account_name, initial_balance=0):
        self.account_name = account_name
        self.balance = initial_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 > 0 and amount <= self.balance:
            self.balance -= amount
            print(f"Withdrew {amount}. New balance is {self.balance}.")
        else:
            print("Invalid withdrawal amount.")

    def get_balance(self):
        return self.balance

# 示例使用
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Final balance is {account.get_balance()}.")

代码解析:

  • __init__ 方法是类的构造函数,用于初始化账户名和初始余额。
  • deposit 方法用于存款,增加账户余额。
  • withdraw 方法用于取款,减少账户余额,但确保不会透支。
  • get_balance 方法返回当前账户余额。

输出结果:

Deposited 50. New balance is 150.
Withdrew 20. New balance is 130.
Final balance is 130.

Document 对象参考手册 Python3 实例