您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 元类的“__call__”和实例的“__init__”的关系?

5b51 2022/1/14 8:22:52 python 字数 3072 阅读 562 来源 www.jb51.cc/python

假设我有一个元类和一个使用它的类: class Meta(type): def __call__(cls, *args): print "Meta: __call__ with", args class ProductClass(object): __metaclass__ = Meta def __init__(self, *args):

概述

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__?

更新:

现在,我为ProductClass添加__new__

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

p = ProductClass(1)

调用ProductClass的__new____init__Meta .__ call __的责任吗?

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

总结

以上是编程之家为你收集整理的python – 元类的“__call__”和实例的“__init__”的关系?全部内容,希望文章能够帮你解决python – 元类的“__call__”和实例的“__init__”的关系?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶