0
class A:
    def __init__(self):
        self.quantity = 1

    def __add__(self, other):
        self.quantity += other.quantity
        del other  # Not deleting.
        return self

    def __radd__(self, other):
        if other == 0:
            return self
        else:
            return self.__add__(other)

    def __str__(self):
        return f'{self.quantity}'

    def __repr__(self):
        return f'<A object: {self.quantity}>'


if __name__ == '__main__':
    a = A()
    b = A()
    array = [a,b]
    print(sum(array))
    print(array)

Result:

2
[<A object: 2>, <A object: 1>]

Expected result:

2
[<A object: 2>]

The function is adding normally but the del is not deleting the other items in the list.

I try to use the other after use the del other and it prints an error. But its not deleting the item from the list.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Thomas Caio
  • 83
  • 1
  • 1
  • 11

1 Answers1

2

The problem is that del doesn't do what you seem to think it does. My guess is that you think it causes the value referenced by the name after del to be deleted. What really happens is that the reference named after del is deleted from the current namespace.
If that reference is the last reference to the value, then eventually (possibly immediately, but possibly not for a very long time), the referenced value will be deleted.
Your del other only deletes the reference named other, which has no detectable effect. It does not (and cannot) change the contents of the list passed in to sum.

cco
  • 5,873
  • 1
  • 16
  • 21