这个问题与来自python中的基类的Inherit namedtuple相反,其目的是从namedtuple继承子类,反之亦然.
在正常继承中,这有效:
class Y(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
class Z(Y):
def __init__(self, a, b, c, d):
super(Z, self).__init__(a, b, c)
self.d = d
Run Code Online (Sandbox Code Playgroud)
[OUT]:
>>> Z(1,2,3,4)
<__main__.Z object at 0x10fcad950>
Run Code Online (Sandbox Code Playgroud)
但如果基类是namedtuple:
from collections import namedtuple
X = namedtuple('X', 'a b c')
class Z(X):
def __init__(self, a, b, c, d):
super(Z, self).__init__(a, b, c)
self.d = d
Run Code Online (Sandbox Code Playgroud)
[OUT]:
>>> Z(1,2,3,4)
Traceback (most recent call …Run Code Online (Sandbox Code Playgroud) 参考手册中明确记录了这一点:
\n\n\n非空 _ slot _ 不适用于从 \xe2\x80\x9cvariable-length\xe2\x80\x9d 内置类型(例如 int、bytes 和 tuple)派生的类。
\n
情况确实如此,写道:
\nclass MyInt(int):\n __slots__ = 'spam',\nRun Code Online (Sandbox Code Playgroud)\n结果是:
\nTypeError: nonempty __slots__ not supported for subtype of 'int'\nRun Code Online (Sandbox Code Playgroud)\n这是为什么呢?为什么空槽可以使用但非空槽禁止使用?
\n