我做了一个小型的加密器类,它需要一个字(一个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'。或者在班级外部保留一个列表累加器。 –