Python 3, super .__ del __ ()

I have a __del__ method in my class to remove some C ++ objects created by calling C ++ new in the ctypes interface. I want to delete these objects when an instance of my class is destroyed. I have a fragment of the class shown here:

 class Graph(QtCore.QObject): def __init__(self): super().__init__() #list of objects created by calls to ctypes to create pointers to C++ objects which are instantiated with C++ new self.graphs = [] def __del__(self): print("in delete method") for graph in self.graphs: # call the C++ delete to free the storage used by this graph myctypes.graphDelete(graph) super().__del__() 

When an instance of the Graph class is deleted, the __del__ method is __del__ , and I see my print statement, and when I set a breakpoint in the destructor method in C ++ code, as expected, it deletes the object. However, when my __del__ method calls super().__del__() , I get an error:

 super().__del__() AttributeError: 'super' object has no attribute '__del__' 

How to ensure that the parent class (QtCore.QObject) is deleted if I define my own __del__ method in the child class or the parent class is automatically deleted?

+5
source share
2 answers

The class you are __del__() does not have __del__() . Therefore, an attempt to cause this error.

Now, if you expect your class to be used in a multiple inheritance scenario, the next class in method resolution order (MRO) may not be your class parent. And this class, whatever it may be, may have a __del__() method. So, if this case bothers you, you can use try and catch an AttributeError , or use hasattr() , or use getattr() with a dummy lambda as the default value.

Here is an example of each of them:

 # there is a minor bug here, can you guess what it is? try: super().__del__(self) except AttributeError: pass # better version of the above s = super() try: s.__del__ except AttributeError: pass else: s.__del__(self) s = super() if hasattr(s, "__del__"): s.__del__(self) getattr(super(), "__del__", lambda self: None)(self) 
+4
source

The role of __del__ is not to delete the object: it is called before the object is automatically deleted. Therefore, this is great if your parent class does not define __del__ . Feel free to call super().__del__() if it overhears you.

For the record, the reason that objects do not have a default __del__ is because objects with __del__ were not garbage collected in the case of reference loops (before Python 3.4). For more information, read the gc.garbage documentation in Python 3.3 and gc.garbage in Python 3.4 .

+1
source

Source: https://habr.com/ru/post/1247441/


All Articles