元类的"__call__"关系和实例的"__init__"? [英] Relationship of metaclass's "__call__" and instance's "__init__"?

查看:65
本文介绍了元类的"__call__"关系和实例的"__init__"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个元类和一个使用它的类:

Say I've got a metaclass and a class using it:

class Meta(type):
    def __call__(cls, *args):
        print "Meta: __call__ with", args

class ProductClass(object):
    __metaclass__ = Meta

    def __init__(self, *args):
        print "ProductClass: __init__ with", args

p = ProductClass(1)

输出如下:

Meta: __call__ with (1,)

问题:

为什么不触发ProductClass.__init__ ...仅仅是因为Meta.__call__引起的?

Why isn't ProductClass.__init__ triggered...just because of Meta.__call__?

更新:

现在,我为ProductClass添加__new__:

Now, I add __new__ for ProductClass:

class ProductClass(object):
    __metaclass__ = Meta

    def __new__(cls, *args):
        print "ProductClass: __new__ with", args
        return super(ProductClass, cls).__new__(cls, *args)

    def __init__(self, *args):
        print "ProductClass: __init__ with", args

p = ProductClass(1)

调用ProductClass的__new____init__Meta.__call__的责任吗?

Is it Meta.__call__'s responsibility to call ProductClass's __new__ and __init__?

推荐答案

在OOP中,扩展方法与覆盖方法之间存在差异,您在元类Meta中所做的操作称为覆盖,因为您定义了方法,您没有调用父__call__.要具有所需的行为,您必须通过调用父方法来扩展__call__方法:

There is a difference in OOP between extending a method and overriding it, what you just did in your metaclass Meta is called overriding because you defined your __call__ method and you didn't call the parent __call__. to have the behavior that you want you have to extend __call__ method by calling the parent method:

class Meta(type):
    def __call__(cls, *args):
        print "Meta: __call__ with", args
        return super(Meta, cls).__call__(*args)

这篇关于元类的"__call__"关系和实例的"__init__"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆