簡體   English   中英

Python函數在2個用戶之間發送東西?

[英]Python function to send things between 2 users?

我正在嘗試學習python(以及一般編程)。 現在,我正在嘗試建立一個簡單的銀行,用戶可以在其中進行匯款/存款/取款。 我已經創建了存款和提款功能,並且正在工作。 現在,我對如何編寫發送功能完全感到困惑,因為用戶將要匯款,而另一個將要接收錢。 我應該為發送和接收編寫兩個獨立的函數,但是如何同時觸發這兩個函數? (另一個包含兩者的功能)?

希望您能為我提供幫助,到目前為止,這是我的代碼:類:

class Account(object):
def __init__(self, name, account_number, initial_amount):
    self.name = name
    self.no = account_number
    self.balance = initial_amount

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

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

def dump(self):
    s = '%s, %s, balance: %s' % \
        (self.name, self.no, self.balance)
    print s

def get_balance(self):
    print(self.balance)

def send(self, sender, receiver, amount):
    self.sender = sender
    self.receiver = receiver
    self.balance -= amount

main.py:

from classes.Account import Account

a1 = Account('John Doe', '19371554951', 20000)
a2 = Account('Jenny Doe',  '19371564761', 20000)
a1.deposit(1000)
a1.withdraw(4000)
a2.withdraw(10500)
a2.withdraw(3500)

a1.get_balance()

我知道這可能是基本的,但我希望可以在這里獲得幫助。

謝謝

您已經有depositwithdraw方法,因此不妨使用它們。

轉移資金實質上是從一個帳戶中提取資金,然后將其存入另一個帳戶。

這可以通過一個靜態方法來實現,該方法接受2個帳戶,並且該金額將封裝“轉帳”的概念:

class Account:
    .
    .
    .

    @staticmethod
    def transfer(from_account, to_account, amount):
        from_account.withdraw(amount)
        to_account.deposit(amount)
        # TODO perhaps you will want to use a try-except block 
        # to implement a transaction: if either withdrawing or depositing 
        # fails you will want to rollback the changes.

用法:

from classes.Account import Account

a1 = Account('John Doe', '19371554951', 20000)
a2 = Account('Jenny Doe',  '19371564761', 20000)
print(a1.balance)
print(a2.balance)
Account.transfer(a1, a2, 10)
print(a1.balance)
print(a2.balance)
#  20000
#  20000
#  19990
#  20010 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM