سؤال

In my code, I've defined a class with its own repr method. The representation of the class should be a list.

def __repr__(self):
    if self.front <= self.tail:
        q = self._queue[self.front:self.tail+1]

    elif self.front > self.tail:
        q = self._queue[self.front:]
        q.extend(self._queue[:self.tail + 1])

    return (q.__repr__())

I've written the following unittest to test this method.

def test_enqueue(self):
    q = BoundedQueue(1)
    q.enqueue(1)
    self.assertEqual(q, [1])

However, I end up with an assertion error:

Traceback (most recent call last):
  File "test_internmatch_queue.py", line 13, in test_enqueue
    self.assertEqual(q, [1])
AssertionError: [1] != [1]

I'm not sure what the problem is... to my human eyes, [1]==[1]! I've tried several other variations in my repr method (below), and they all returned errors as well.

return repr(q)
return str(q)
هل كانت مفيدة؟

المحلول

q is a BoundedQueue. [1] is a list. They can't be equal unless you override __eq__. repr is not used for equality testing.

نصائح أخرى

As recursive states, __repr__ isn't used to detect whether two values are equal.

You have several options:

  1. Define __eq__ which is what python calls to check equality. I don't recommend this as I don't really see a BoundedQueue as being equal to a list
  2. Define an items() method which returns the list. Then check for equality against the list
  3. Add a way to build a BoundedQueue from a list. Then write __eq__ to check for equality between two BoundedQueues.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top