0

I have a class where in the initialization I set one member to a bytearray, and then another to its reverse by using the bytearray.reverse() function.

When I instantiate the class, the "reversed" array is not reversed. If I then call reverse on the member after instantiation, it reverses fine. What is happening? class and ipython output is below

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;')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Daniel B.
  • 1,254
  • 1
  • 16
  • 35

1 Answers1

2

You are acting on the same reference when you call .reverse on self.decrKey because you previously made the assignment:

self.decrKey = self.encrKey

As a result, you're reversing both encrKey and decrKey. Instead, copy decrKey with [:] and then call .reverse:

self.encrKey = key[:8]
self.decrKey = self.encrKey[:]
self.decrKey.reverse()
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253