我正在開發一個應用程式來保存和分析我的加密貨幣資料。我使用 2 個不同的應用程式,hotbit 和 binance。例如,因為我在 hotbit 和 binance 上都購買了 BTC,所以我想在 BTC 的末尾添加 HB 以指定它需要進入我創建的 hotbit 表。它應該看起來像“BTCHB”。
def which_application(self):
print("Which application was this transaction made on? Type either 'hotbit' or 'binance'")
which_application_prompt = input("").strip().lower()
if which_application_prompt == 'hotbit':
self = self 'HB'
return(self)
elif which_application_prompt == 'binance':
pass
else:
print("Invalid input.")
which_application(self)
我已經創建了這個函式,并且在函式內部一切正常。但是,當我呼叫該函式并添加一個值代替 self 時,它不會向它添加 HB。有任何想法嗎?
uj5u.com熱心網友回復:
您缺少self在遞回呼叫中重新分配值,固定版本可能是:
def which_application(self):
print("Which application was this transaction made on? Type either 'hotbit' or 'binance'")
which_application_prompt = input("").strip().lower()
if which_application_prompt == 'hotbit':
self = self 'HB'
return(self)
elif which_application_prompt == 'binance':
return self
else:
print("Invalid input.")
self = which_application(self)
return self
作品:
$ python3 demo.py
Which application was this transaction made on? Type either 'hotbit' or 'binance'
hotbit
testHB
如果您which_application在 else 陳述句中再次呼叫,則可能回傳的值將丟失,因為您沒有將其分配給 self。
另一個缺陷是當您輸入binance任何內容時都不會回傳 - 確切地說是無。
$ python3 demo.py
Which application was this transaction made on? Type either 'hotbit' or 'binance'
binance
None
最后,while 回圈比遞回好。回圈直到回傳。
uj5u.com熱心網友回復:
當您遞回(從自身內部呼叫函式)時,您也在“重新創建”其區域變數,因此self不再參考self與父呼叫中相同的物件。
使用回圈而不是遞回(并考慮使用比 更容易混淆的引數名稱self):
def which_application(transaction):
while True:
print("Which application was this transaction made on? Type either 'hotbit' or 'binance'")
which_application_prompt = input("").strip().lower()
if which_application_prompt == 'hotbit':
transaction = transaction 'HB'
return(transaction)
elif which_application_prompt == 'binance':
break
else:
print("Invalid input.")
# since we're neither `break`'ing nor `return`'ing from here,
# the loop will start over
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327723.html
