Python create a class to simulate a bank account, supporting operations such as deposit, withdrawal, and balance inquiry

Document 对象参考手册Python3 Examples

We will create a class namedBankAccountclass to simulate the basic operations of a bank account. This class will include functions for deposit, withdrawal, and balance inquiry. We will use instance variables to store the account balance and provide methods to manipulate these variables.

Example

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

# Example usage
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Current balance: {account.get_balance()}")

Code explanation:

  • __init__The method is the constructor of the class, used to initialize the account owner and balance.owneris the account owner's name,balanceis the account's initial balance, defaulting to 0.
  • depositThe method is used for deposits. It accepts an amount parameter; if the amount is positive, it adds it to the balance and prints the new balance. If the amount is negative or zero, it prints an error message.
  • withdrawThe method is used for withdrawals. It checks whether the withdrawal amount is greater than the balance; if so, it prints an insufficient funds message. If the amount is positive and does not exceed the balance, it subtracts the amount from the balance and prints the new balance.
  • get_balanceThe method returns the current account balance.

Output result:

Deposited 50. New balance is 150.
Withdrew 20. New balance is 130.
Current balance: 130

Document 对象参考手册Python3 Examples

Other extensions