如何在BankAccount类中创建事务方法?



我是一个尝试用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对象转移到另一个CC_1对象?

有没有人会好心地帮助一个有动力的新人?

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

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

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

然后,假设您想将100美元从account1转移到account2,您可以这样调用函数:在你的代码片段中,它看起来像这样:

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

最新更新