如何在银行账户class中创建交易方式?

How to mak a transaction method in a BankAccount class?

我是一个尝试在python学习OOP的菜鸟。为了学习和实践,我正在执行一项任务,要求我在 class BankAccount 中创建一个交易方法,将钱从一个银行账户转移到另一个银行账户。

这是我到目前为止编写的代码:

class BankAccount:
    def __init__(self, first_name, last_name, number, balance):
        self._first_name = first_name
        self._last_name = last_name
        self._number = number
        self._balance = balance         

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        self._balance -= amount

    def get_balance(self):
        return self._balance

    def transfer(self, amount_out):
        self.withdraw(amount_out)

        amount_in = amount_out                          #This is where i am unsure/stuck
        self.deposit(amount_in)

    def print_info(self):
        first = self._first_name
        last = self._last_name
        number = self._number
        balance = self._balance

        s = f"{first} {last}, {number}, balance: {balance}"

        print(s)

def main():

    account1 = BankAccount("Jesse", "Pinkman", "19371554951", 20_000)
    account2 = BankAccount("Walter", "White", "19371564853",500)

    a1.transfer(200)

    a1.print_info()
    a2.print_info()

main()

我的问题是: 您如何才能以将钱从一个 BankAccount 对象转移到另一个对象的方式进行交易 class?

有好心人可以帮助有上进心的菜鸟吗?

我们非常欢迎和感谢所有帮助。

如果我在做这个任务,我会这样写transfer

def transfer(self, other, amount):
    self.withdraw(amount)
    other.deposit(amount)

然后,假设您想将 100 美元从 account1 转移到 account2,您可以像这样调用函数:account1.transfer(account2, 100).

在您的代码片段中,它看起来像这样:

class BankAccount:
    def __init__(self, first_name, last_name, number, balance):
        self._first_name = first_name
        self._last_name = last_name
        self._number = number
        self._balance = balance

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        self._balance -= amount

    def get_balance(self):
        return self._balance

    def transfer(self, other, amount_out):
        self.withdraw(amount_out)
        other.deposit(amount_out)

    def print_info(self):
        first = self._first_name
        last = self._last_name
        number = self._number
        balance = self._balance

        s = f"{first} {last}, {number}, balance: {balance}"

        print(s)


def main():

    a1 = BankAccount("Jesse", "Pinkman", "19371554951", 500)
    a2 = BankAccount("Walter", "White", "19371564853", 500)

    a1.transfer(a2, 200)

    a1.print_info()
    a2.print_info()


main()