bytearray.reverse() 在 class 中不工作,在对象上调用时工作
bytearray.reverse() not working within a class, is working when called on object
我有一个 class,在初始化中我将一个成员设置为字节数组,然后使用 bytearray.reverse() 函数将另一个成员设置为字节数组的相反方向。
当我实例化 class 时,"reversed" 数组没有反转。如果我在实例化后对成员调用 reverse,它会很好地反转。怎么了? class 和 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;')
当您在 self.decrKey
上调用 .reverse
时,您正在对同一个参考进行操作,因为您之前进行了分配:
self.decrKey = self.encrKey
因此,您正在反转 encrKey
和 decrKey
。相反,使用 [:]
和 复制 decrKey
,然后 调用 .reverse
:
self.encrKey = key[:8]
self.decrKey = self.encrKey[:]
self.decrKey.reverse()
我有一个 class,在初始化中我将一个成员设置为字节数组,然后使用 bytearray.reverse() 函数将另一个成员设置为字节数组的相反方向。
当我实例化 class 时,"reversed" 数组没有反转。如果我在实例化后对成员调用 reverse,它会很好地反转。怎么了? class 和 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;')
当您在 self.decrKey
上调用 .reverse
时,您正在对同一个参考进行操作,因为您之前进行了分配:
self.decrKey = self.encrKey
因此,您正在反转 encrKey
和 decrKey
。相反,使用 [:]
和 复制 decrKey
,然后 调用 .reverse
:
self.encrKey = key[:8]
self.decrKey = self.encrKey[:]
self.decrKey.reverse()