Python 触发 __new__ 而没有 __init__?

Python trigger __new__ without __init__?

我有一个class答:

class A:
    def __new__(*args, **kwargs)
    def __init__(a1, a2)

现在我想传入一个新参数a3来创建工厂

class A:
    def __new__(*args, **kwargs):
       # Do sth with a3

    def __init__(a1, a2)

所以这里 a3 只在 __new__ 中使用,但我意识到我必须先将 a3 传递给 __init__ 才能让它工作,所以我需要将 __init__ 修改为 def __init__(a1, a2, a3)def __init__(a1, a2, **kwargs)。我通过 a3 但从未在 __init__

中使用它很奇怪

所以基本上我可以在不改变 __init__ 的情况下触发 __new__?

__new____init__type.__call__ 调用。通常,当 __new__ returns 目标实例 class 时,metaclass 在结果上调用 __init__。您可以通过更改 metaclass:

来覆盖此行为
class MetaA(type):
    def __call__(cls, *args, **kwargs):
        obj = cls.__new__(cls, *args, **kwargs)
        # you can omit `__init__` entirely, or you can replicate
        # what `type` does, but strip the last positional argument:
        if isinstance(obj, cls):
            if len(args) > 2:
                args = args[:2]
            cls.__init__(obj, *args, **kwargs)
        return obj

class A(metaclass=MetaA):
    ...