0

I'm trying to define a class method which assigns a random list of numbers to a given (pre-existing) object, in order for it to run under MicroPython in an ESP8266. The issue I'm facing is the value of this object is empty after several append()s. The code I'm using goes as follows:

from urandom import getrandbits

class Buffer(list):
    def randomize(self, randdims):
        bits, nelem = 8, 1
        self = Buffer() # In case self had previous content.
        for n in randdims: nelem *= n
        for _ in range(randdims[0]):
            self.append([
                ((getrandbits(bits) / (2 ** bits)) * 2) - 1
                for _ in range(n_elem // randdims[0])
            ])

but after running this method like

>>> buf = Buffer((1,2,3,4))
>>> print(buf.randomize((2,3)))
[1,2,3,4] # instead of a random series of numbers.

self does not seem to have changed at all, even though it grew in each iteration. Why would self be incremented inside the loop but not after exiting the method?

tulians
  • 439
  • 5
  • 23
  • 1
    When you assign to `self`, it no longer refers to the object on which the `.randomize()` method was invoked: it's a brand new object, which will be thrown away as soon as the method ends, because nothing holds a reference to it. – jasonharper Jan 02 '18 at 23:51

1 Answers1

2

You are rebinding the name self to a new instance of Buffer then proceeding to invoke the append method on that new instance. Remember that self is just like any other name that can be rebound and when it is rebound it doesn't retain any special properties pointing back to the original object. The following line can be removed and your code should work as expected.

self = Buffer() # In case self had previous content.

Even with the comment I can't figure out what you were looking to do with that line.

Colin Schoen
  • 2,526
  • 1
  • 17
  • 26