python – 元类的“__call__”和实例的“__init__”的关系?
发布时间:2020-05-23 06:00:13 所属栏目:Python 来源:互联网
导读:假设我有一个元类和一个使用它的类: class Meta(type): def __call__(cls, *args): print Meta: __call__ with, argsclass 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 __的责任吗? 解决方法在扩展方法和覆盖它之间的OOP有所不同,你在元类Meta中所做的事情被称为覆盖,因为你定义了__call__方法而你没有调用父__call__.通过调用父方法来获得您希望必须扩展__call__方法的行为:class Meta(type):
def __call__(cls,args
return super(Meta,cls).__call__(*args) (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
