Why should I use __new__ instead of __init__ in this example?

Viewed 5069

I have been studying __new__ recently, and I've read lots of code where __new__ is used instead of __init__. Sometimes I think both work, but I don't know why the original author uses __new__.

Can someone explain why the below code uses __new__ instead of __init__? I want a reason for this example. I know the difference between __new__ and __init__, but I don't know why __new__ is used here.

Example:

    class MiniSubtest(object):
        def __new__(cls, *args, **kargs):
            self = super(MiniSubtest, cls).__new__(cls)
            ret = None
            if args is None:
                args = []
            try:
                ret = self.test(*args, **kargs)
            finally:
                if hasattr(self, "clean"):
                    self.clean()
            return ret

and I think if I use __init__, it still works, whey it used __new__?

2 Answers

This controls the creation and return of the new instance:

  • First the instance is created.
  • The try clause catching an exception during testing the new instance.
  • Then if there is exception, it cleans the instance's garbage.
  • Then it returns None rather than the instance.

So it decides to return an instance or to discard it.

Related