我做了一個小型的加密器類,它需要一個字(一個string
)作爲輸入,並返回list
string
s。加密速度慢,所以我緩存結果,以防我想再次加密相同的單詞。 (在下面的代碼中,實際加密已被替換爲一些虛擬代碼) 以下代碼不起作用,因爲encrypt
會將非常量引用返回給內部。 什麼將是一個很好的pythonian方式來解決這個問題? 我需要能夠與=
和+=
一起使用它,如圖所示。Python成員函數返回非const引用內部 - 需要pythonian修復
class Encryptor():
def __init__(self):
self.cache = {}
def encrypt(self, word):
if word in self.cache:
return self.cache[word]
encrypted = list("<" + word + ">")
self.cache[word] = encrypted
return encrypted
encryptor = Encryptor()
encrypted_text = encryptor.encrypt("this")
encrypted_text += encryptor.encrypt("is")
encrypted_text += encryptor.encrypt("good")
encrypted_text += encryptor.encrypt("this")
encrypted_text += encryptor.encrypt("is")
encrypted_text += encryptor.encrypt("not")
print("".join(encrypted_text))
預期輸出:
<this><is><good><this><is><not>
實際輸出:通過在列表returne調用+=
self.extend(other)
return self
這樣:
<this><is><good><this><is><good><is><not>
做一個元組,而不是列表,你在哪裏加密=元組(「<」+ word +「>」) – user1767754
詳細說明@ user1767754和@jotasi--因爲你在'list'上使用'+ =',列表是可變的,重新改變這個'list'。 「list」對象存儲在'encryptor.cache [「this」]'中,因此也會改變。要麼返回一個副本,要麼使用'tuple's。 – Kendas
爲什麼你甚至使用中間名單?只需使用'str'。或者在班級外部保留一個列表累加器。 –