gpt4 book ai didi

python - 如何继承 ABCMeta

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:06 25 4
gpt4 key购买 nike

通常,为了子类化一个类,我会做类似的事情

class Subby(Parenty):
def __init__(self):
Parenty.__init__(self)

但是现在我正在尝试子类化一个元类,特别是 ABCMeta,所以我在做

import ABCMeta

class Subby(ABCMeta):
def __init__(self):
ABCMeta.__init__(self) #this never seems to run

def __new__(mcls, name, bases, namespace):
cls = ABCMeta.__new__(mcls, name, bases, namespace)
return cls

但是,当我尝试将 Subby 子类化为元类时

class newClass(metaclass=Subby):
pass

我收到错误 TypeError: __init__() takes 1 positional argument but 4 were given

这是为什么,我如何正确地子类化 ABCMeta?

最佳答案

来自数据模型:

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

因此,正如@user2357112 所说,签名必须匹配

尽管如此,如果您只是想创建一个 ABC,真的没有理由定义 __init____new__。只需创建它并使用 .register 来注册一致的类。或者,创建一些抽象方法和一个检查一致性的 __subclasshook__abc module documentation 中已有一个很好的例子.

关于python - 如何继承 ABCMeta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43858592/

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