Python-Implementierung einer Bankkontoklasse, die Einzahlungen und Auszahlungen unterstützt

Document 对象参考手册Python3-Beispiele

Wir werden eine einfache Bankkontoklasse erstellen. Diese Klasse enthält grundlegende Kontoinformationen wie Kontoname und Kontostand und unterstützt Einzahlungs- und Auszahlungsvorgänge.

Beispiel

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"Eingezahlt {amount}. Neuer Kontostand ist {self.balance}.")
        else:
            print("Der Einzahlungsbetrag muss positiv sein.")

    def withdraw(self, amount):
        if amount > 0 and amount <= self.balance:
            self.balance -= amount
            print(f"Abgehoben {amount}. Neuer Kontostand ist {self.balance}.")
        else:
            print("Ungültiger Auszahlungsbetrag.")

    def get_balance(self):
        return self.balance

# Beispielverwendung
account = BankAccount("John Doe", 100)
account.deposit(50)
account.withdraw(20)
print(f"Endgültiger Kontostand ist {account.get_balance()}.")

Codeanalyse:

  • __init__Die Methode ist der Konstruktor der Klasse und wird verwendet, um den Kontonamen und den Anfangssaldo zu initialisieren.
  • depositDie Methode wird für Einzahlungen verwendet und erhöht den Kontostand.
  • withdrawDie Methode wird für Abhebungen verwendet, verringert den Kontostand, stellt aber sicher, dass keine Überziehung erfolgt.
  • get_balanceDie Methode gibt den aktuellen Kontostand zurück.

Ausgabeergebnis:

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

Document 对象参考手册Python3-Beispiele

Andere Erweiterungen