假设我有一个元类和一个使用它的类:
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)