【问题标题】:How to mak a transaction method in a BankAccount class?如何在 BankAccount 类中创建交易方法?
【发布时间】:2021-12-09 01:40:33
【问题描述】:

我是一个尝试用python学习OOP的菜鸟。为了学习和实践,我正在做一个任务,要求我在 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 对象转移到另一个对象?

有没有好心人帮助一个有动力的菜鸟?

所有帮助都受到广泛欢迎和赞赏。

【问题讨论】:

  • 转移到自我有意义吗?添加另一个帐户作为参数怎么样? def transfer(self, amount_out, transfer_to_account): 还有资金不足怎么办?跟踪交易历史呢?
  • @Abel:感谢您的帮助:-) 我之前尝试过类似的方法,但我不知道如何使用transfer_to_account 参数来转移资金。你介意告诉我怎么做吗?

标签: python object oop constructor instance-variables


【解决方案1】:

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

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

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

在你的 sn-p 代码中,它看起来像这样:

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()

【讨论】:

  • 感谢您提供清晰而完善的答案!
猜你喜欢
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多