默认的 type.__call__ 做的不仅仅是调用 __new__ 和 __init__ 吗?

eve*_*ody 5 python metaclass

我正在编写一个元类,我想在 __new__ 和 __init__ 之间调用一个额外的方法。

如果我在 __new__ 之前或 __init__ 之后调用该方法,我可以编写例如

class Meta(type):
    def __call__(cls):
        ret = type.__call__()
        ret.extraMethod()
Run Code Online (Sandbox Code Playgroud)

我的诱惑是写

class Meta(type):
    def __call__(cls):
        ret = cls.__new__(cls)
        ret.extraMethod()
        ret.__init__()
        return ret
Run Code Online (Sandbox Code Playgroud)

并自己重现 type.__call__ 的功能。但恐怕我省略了 type.__call__ 的一些微妙之处,这将导致在实现我的元类时出现意外行为。

我不能从 __init__ 或 __new__ 调用 extraMethod 因为我希望我的元类的用户能够像在普通 Python 类中一样覆盖 __init__ 和 __new__,但仍然在 extraMethod 中执行重要的设置代码。

谢谢!

ren*_*kiy 3

如果您确实希望完全按照您所说的去做,我可以建议您采用以下解决方案:

def call_after(callback, is_method=False):
    def _decorator(func):
        def _func(*args, **kwargs):
            result = func(*args, **kwargs)
            callback_args = (result, ) if is_method else ()
            callback(*callback_args)
            return result
        return _func
    return _decorator


class Meta(type):

    def __new__(mcs, class_name, mro, attributes):
        new_class = super().__new__(mcs, class_name, mro, attributes)
        new_class.__new__ = call_after(
            new_class.custom_method,
            is_method=True
        )(new_class.__new__)
        return new_class


class Example(object, metaclass=Meta):

    def __new__(cls, *args, **kwargs):
        print('new')
        return super().__new__(cls, *args, **kwargs)

    def __init__(self):
        print('init')

    def custom_method(self):
        print('custom_method')


if __name__ == '__main__':
    Example()
Run Code Online (Sandbox Code Playgroud)

该代码将生成以下结果:

new
custom_method
init
Run Code Online (Sandbox Code Playgroud)