假设我有一个元类和一个使用它的类:
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)
Run Code Online (Sandbox Code Playgroud)
输出如下:
Meta: __call__ with (1,)
Run Code Online (Sandbox Code Playgroud)
题:
为什么不被ProductClass.__init__触发...只是因为Meta.__call__?
更新:
现在,我__new__为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)
Run Code Online (Sandbox Code Playgroud)
是否有Meta.__call__责任致电ProductClass __new__和__init__?
扩展方法和覆盖方法之间的OOP存在差异,您刚才在元类中执行的操作Meta被称为覆盖,因为您定义了__call__方法并且未调用父方法__call__.__call__通过调用父方法来获得您希望扩展方法的行为:
class Meta(type):
def __call__(cls, *args):
print "Meta: __call__ with", args
return super(Meta, cls).__call__(*args)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2317 次 |
| 最近记录: |