如何继承 ABCMeta
How to subclass ABCMeta
通常,为了子class一个class我会做类似
的事情
class Subby(Parenty):
def __init__(self):
Parenty.__init__(self)
但现在我正在尝试子class一个元class,特别是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
但是,当我随后尝试将 class Subby
作为 metaclass like
class newClass(metaclass=Subby):
pass
我收到错误 TypeError: __init__() takes 1 positional argument but 4 were given
。
为什么会这样,我如何正确地子class 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.
中已经有一个很好的例子
通常,为了子class一个class我会做类似
的事情class Subby(Parenty):
def __init__(self):
Parenty.__init__(self)
但现在我正在尝试子class一个元class,特别是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
但是,当我随后尝试将 class Subby
作为 metaclass like
class newClass(metaclass=Subby):
pass
我收到错误 TypeError: __init__() takes 1 positional argument but 4 were given
。
为什么会这样,我如何正确地子class ABCMeta?
来自数据模型:
If
__new__()
returns an instance ofcls
, 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.