0

Say we have a class Foo

class Foo:
    def __del__(self):
        # do some kind of deleting

    def run(self):
        # run something      

And foo has been added to a list. Its methods will be used later in the program.

l = [Foo()]

Foo is now inside a list.
If I wanted to use the method run I simply call l along with its index and method

l[0].run()

Now if I want to run the __del__ method. I could call Foo's method __del__

l[0].__del__()


My question is:

why isn't del l[0] not the same as l[0].__del__()


Edit:

After messing around a little further, I've found that list[0].__del__() and del list[0] do produce the same results, however calling __del__ does not remove the item in the list, del does however

class Foo:

    def __del__(self):
        print("Deleting")

list = [Foo()]

print(list)
list[0].__del__()
print(list)
del list[0]
print(list)

>
[<Foo object at 0x7f4ad04d97f0>]
Deleting
[<Foo object at 0x7f4ad04d97f0>]
Deleting
[]
>
tisaconundrum
  • 2,156
  • 2
  • 22
  • 37
  • *How come I can't simply do something like this to run Foo's method?* To run *what* method? – Martijn Pieters Feb 15 '18 at 20:01
  • I was using `l[0].run()` as a comparison of running `l[0].__del__()` – tisaconundrum Feb 15 '18 at 20:02
  • 3
    And `del` doesn't exist to call `__del__`. `__del__` is a hook method *when the object is removed from memory*. `del` removes a reference to an object, and only when the reference count drops to 0 will the object be removed from memory. – Martijn Pieters Feb 15 '18 at 20:03
  • So does that mean that I should just rename the function `__del__` – tisaconundrum Feb 15 '18 at 20:04
  • 1
    You would not normally call `__del__()` directly, that won't delete the object. That's simply calling the hook method in a different context. Your object still is referenced, still exists in memory. – Martijn Pieters Feb 15 '18 at 20:04
  • I am skeptical you even need to implement `__del__()`, what, exactly, are you trying to do? – juanpa.arrivillaga Feb 15 '18 at 20:04
  • @tisaconundrum: only give your class a `__del__` method if you need to clean up resources when your object is deallocated. If you are not using it for that purpose, then you are using it incorrectly and should probably not use that name, no. – Martijn Pieters Feb 15 '18 at 20:05
  • 1
    Also, I think `del l[0]` calls `l.__delitem__(0)` – juanpa.arrivillaga Feb 15 '18 at 20:06
  • 2
    @juanpa.arrivillaga: yes, and if that removes the last reference to the `Foo` instance, then the `__del__()` method is called *too*. – Martijn Pieters Feb 15 '18 at 20:07

0 Answers0