相关疑难解决方法(0)

继承自namedtuple基类 - Python

这个问题与来自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)

python oop inheritance super namedtuple

20
推荐指数
3
解决办法
1万
查看次数

为什么非空槽不能与 int、tuple、bytes 子类一起使用?

参考手册中明确记录了这一点:

\n
\n

非空 _ slot _ 不适用于从 \xe2\x80\x9cvariable-length\xe2\x80\x9d 内置类型(例如 int、bytes 和 tuple)派生的类。

\n
\n

情况确实如此,写道:

\n
class MyInt(int):\n    __slots__ = 'spam',\n
Run Code Online (Sandbox Code Playgroud)\n

结果是:

\n
TypeError: nonempty __slots__ not supported for subtype of 'int'\n
Run Code Online (Sandbox Code Playgroud)\n

这是为什么呢?为什么空槽可以使用但非空槽禁止使用?

\n

python class slots python-3.x

6
推荐指数
1
解决办法
1287
查看次数

标签 统计

python ×2

class ×1

inheritance ×1

namedtuple ×1

oop ×1

python-3.x ×1

slots ×1

super ×1