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何时使用引用而不是副本。 –