2017-03-05 75 views
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;') 

回答

2

你是作用于当你调用.reverseself.decrKey因为你以前所做的分配相同的参考:

self.decrKey = self.encrKey 

其结果是,你在倒车encrKeydecrKey。相反,复制decrKey[:]然后呼叫.reverse

self.encrKey = key[:8] 
self.decrKey = self.encrKey[:] 
self.decrKey.reverse() 
+0

我想这可能是类似的东西,但是...为什么它的工作对象实例化后? –

+0

@DanielB。它通过颠倒这两个属性在两种情况下都起作用。调用'cipher.decrKey.reverse()'后查看'cipher.encrKey'的输出结果。它也改变。 –

+0

哦。好。我觉得很愚蠢。我想我需要看看python何时使用引用而不是副本。 –