Pythonでクラスを作成して銀行口座をシミュレートし、入金、出金、残高照会などの操作をサポートします

Document 对象参考手册Python3 例

という名前の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()}")

コード解析:

  • __init__このメソッドはクラスのコンストラクターで、口座所有者と残高を初期化するために使用されます。ownerは口座所有者の名前で、balanceは口座の初期残高で、デフォルトは0です。
  • depositメソッドは預金に使用されます。金額パラメータを受け取り、金額が正の場合は残高に加算して新しい残高を出力します。金額が負またはゼロの場合はエラーメッセージを出力します。
  • withdrawメソッドは引き出しに使用されます。引き出し金額が残高より大きいかどうかを確認し、大きい場合は残高不足のメッセージを出力します。金額が正で残高以下であれば、残高からその金額を差し引き、新しい残高を出力します。
  • get_balanceメソッドは現在の口座残高を返します。

出力結果:

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

Document 对象参考手册Python3 例

その他の拡張