gpt4 book ai didi

python - 元类的 "__call__"和实例的 "__init__"的关系?

转载 作者:太空狗 更新时间:2023-10-29 22:14:06 25 4
gpt4 key购买 nike

假设我有一个元类和一个使用它的类:

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):
print "ProductClass: __init__ with", args

p = ProductClass(1)

调用 ProductClass 的 __new____init__Meta.__call__ 的职责吗?

最佳答案

在 OOP 中扩展方法和重写它是有区别的,你刚刚在你的元类 Meta 中所做的被称为重写,因为你定义了你的 __call__ 方法并且你没有调用父级 __call__。要获得您想要的行为,您必须通过调用父方法来扩展 __call__ 方法:

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

关于python - 元类的 "__call__"和实例的 "__init__"的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7485324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com