元类的"__call__"关系和实例的"__init__"? [英] Relationship of metaclass's "__call__" and instance's "__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屋!