![](/img/trans.png)
[英]How to implement abstract class methods as static method in inherited class in python?
[英]How to implement transfer method for a account class in python
因此,我正在用python創建一個Account類。 它具有存款,取款和檢查余額的基本功能。 我在使用傳輸方法時遇到了麻煩。 這是我的代碼(對不起,代碼轉儲):
class Account:
"""simple account balance of bank"""
def __init__ (self, name, balance):
self.name = name
self.balance = balance
print('Account of ' + self.name)
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.statement()
def withdrawal(self, amount):
if amount > 0 and self.balance > amount:
self.balance -= amount
self.statement()
else:
print("the ammount in your is not sufficent")
self.statement()
def statement(self):
print("Hi {} your current balance is {}".format(self.name,self.balance))
def transfer(self, amount, name):
self.balance = self.balance - amount
name.balance = name.balance + amount
return name.balance()
現在,它適用於
abc = Account("abc", 0)
abc.deposit(1000)
siddharth = Account("siddharth", 159)
那么我如何運行以下代碼:
siddharth.transfer(11, "abc")
siddharth.transfer(11, Account.abc)
另外,如果帳戶“ abc”不存在,如何創建帳戶“ abc”
您的代碼將是有關注意變量/參數命名的最佳課程。 您的方法transfer(self, amount, name)
應該是transfer(self, amount, account)
。 我認為現在很明顯,正確的代碼是
abc = Account("abc", 0)
abc.deposit(1000)
siddharth = Account("siddharth", 159)
siddharth.transfer(11, abc)
在誤導姓名時要格外小心。
除了您的問題外,我認為帳戶不應該具有轉帳方法。 賬戶只關心存款和取款,而不關心他們如何處理。 IMO Transfer應該是一個具有2個Account
參數的功能,從第一個Account
撤出,在第二個Account
進行存款。 這只是遵循單一責任原則。
遵循相同的原則,請勿將打印功能放入帳戶中。 考慮一下您不知道將在其中使用類的上下文。 如果在Web應用程序中,則打印將重定向到/ dev / null…
最后,始終按照您說的去做。 如果我有一個余額為b的帳戶,我希望在調用存入值為v的存款后,我的帳戶余額將為b + v。無論v的值為多少。您都可以檢查該值而不添加a負值(即提現),因此您必須警告調用者不要添加該值,因此會引發異常。 提款相同。
首先,您可以在某個地方聲明一個包含所有帳戶的數組。 然后,您可以首先嘗試查找一個帳戶是否存在。 如果沒有,請創建一個帳戶並通過。
allAccounts = []
#create bunch of accounts including 'abc'
siddharth = Account("siddharth", 159)
searchResult = [x for x in allAccounts if x.name == 'abc']
#assuming that account names are unique
if len(searchResult) == 0:
acc = Account("abc", 11)
else:
acc = searchResult[0]
siddarth.transfer(11, acc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.