There is a class Foo :
class Foo: def __init__(self, data = None): if data == None: self.__del__() def __del__(self): print('Error') f = Foo() # Error print(f) # <__main__.Foo object at 0x7fc1210de1d0> I have this problem:
If I create an instance of a class, I need to check if the data argument is passed. If not, class creation needs to be canceled. I call the __del__ method from the __init__ method, but the instance remains in memory, this can be checked using print(f) . Already once I did it, maybe I forgot something, but I don’t understand at all: how to fix and what to google?
__del__function is a regular function (well, or a method, if you like) and it means nothing (in some implementations of Python, it is not used at all). The only thing that can be done is to throw an exception into__init__and hope that one day a garbage collector will come after the created instance of the class and delete it (and in some implementations it may not come) - andreymal__init__may affect something ... As I recall, by the time__init__is called, an instance has already been created. Perhaps manipulating__new__might help. - Xander__new__possible, but I worked very little with him, I don’t know - andreymal