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

use*_*609 8 python design-patterns

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
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*era 0

__new__用于控制新实例的创建并期望您返回它,而__init__只让您初始化已经创建的实例

我的猜测是self.test根据参数返回不同类型的实例