I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I’ve tried a few things, one of them being raising an error in the __new__ method:
class a():
def __new__(cls, x):
if x == True:
return cls
else:
raise ValueError
This is what I was hoping would happen:
>>obj1 = a(True)
>>obj2 = a(False)
ValueError Traceback (most recent call last)
obj1 exists but obj2 doesn’t.
Any ideas?
When you override
__new__, dont forget to call to super!Simply returning the class does nothing when it was your job to create an instance. This is what the super class’s
__new__method does, so take advantage of it.