0
我有一個類,在初始化過程中,我將一個成員設置爲bytearray,然後通過使用bytearray.reverse()功能。bytearray.reverse()在類中不工作,在對象上調用時工作
當我實例化類,「顛倒」數組不顛倒。如果我在實例化之後在成員上調用reverse,它會很好地反轉。發生什麼事?類和IPython的輸出低於
class Cipher():
def __init__(self, key=bytearray(b'abc123y;')):
self.setKeys(key)
def setKeys(self, key):
if isinstance(key, bytearray) and len(key) >= 8:
self.encrKey = key[:8]
self.decrKey = self.encrKey
self.decrKey.reverse()
print("Encrypt: ", self.encrKey)
print("Decrypt: ", self.decrKey)
return True
else:
return False
In [13]: cipher = Cipher()
Encrypt: bytearray(b';y321cba')
Encrypt: bytearray(b';y321cba')
In [14]: cipher.decrKey.reverse()
In [15]: cipher.decrKey
Out[15]: bytearray(b'abc123y;')
我想這可能是類似的東西,但是...爲什麼它的工作對象實例化後? –
@DanielB。它通過顛倒這兩個屬性在兩種情況下都起作用。調用'cipher.decrKey.reverse()'後查看'cipher.encrKey'的輸出結果。它也改變。 –
哦。好。我覺得很愚蠢。我想我需要看看python何時使用引用而不是副本。 –