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?
__init__(self, ...)instead?__new__be preferable to raising one in__init__. The result seems the same to me and__init__is where all the other initialization code goes. Why shouldn't this go there as well?__init__should only throw an exception if it runs into trouble initializing the instance. Here, it's an explicit test that's being done. I'm probably just quibbling though. I would say that if you want to do it in the initializer, just try to use whateverxis and let that raise an exception or go through.__init__as the constructor. If the construction of the object needs to be aborted, for any reason, it works just as well to raise an exception there. Overriding__new__is very rarely needed and for everyday normal classes I think it should be avoided. Doing so keeps the class implementation simple.