You can throw an exception if either assertio fail, or - if you really do not want or cannot work with exceptions, you can write the __new__ method in your classes - in Python __init__ technically the "initializer" of the method - and it must fill in its attributes and acquire some resources and other objects that you will need throughout the life cycle. However, Python does define a real constructor, __new__ , which is called before __init__ - and in contrast, __new__ does return a value: the newly created (uninitialized) instance itself.
So, you can put your checks inside __new__ and simply return None - something fails - otherwise return the call result to the __new__ superclass __new__ (you cannot actually allocate memory for an object in pure Python, so in the end you need to call the constructor written in native code in a superclass - usually this is object.__new__ in the base of your class hierarchy.
NB . In Python 2, you should have object as the base class for your hierarchy - otherwise, not only __new__ will not be called, like many functions added later in Python, objects simply do not work. In short, class MyClass(object): never class MyClass: - if you are not in Python3.
jsbueno
source share