通过子类化修改namedtuple的构造函数参数?

Ben*_*ank 18 python super new-operator namedtuple

我想创建一个namedtuple代表短位域中的各个标志的代码.我正在尝试将其子类化,以便在创建元组之前解压缩位域.但是,我目前的尝试不起作用:

class Status(collections.namedtuple("Status", "started checking start_after_check checked error paused queued loaded")):
    __slots__ = ()

    def __new__(cls, status):
        super(cls).__new__(cls, status & 1, status & 2, status & 4, status & 8, status & 16, status & 32, status & 64, status & 128)
Run Code Online (Sandbox Code Playgroud)

现在,我的经验super()是有限的,我的经验__new__实际上是不存在的,所以我不太清楚该怎么做(对我来说)神秘的错误TypeError: super.__new__(Status): Status is not a subtype of super.谷歌搜索和挖掘文档并没有产生什么启发.

救命?

Ray*_*ger 18

你差不多了:-)只有两个小修正:

  1. 方法需要返回语句
  2. 超级调用应该有两个参数,CLS状态

生成的代码如下所示:

import collections

class Status(collections.namedtuple("Status", "started checking start_after_check checked error paused queued loaded")):
    __slots__ = ()

    def __new__(cls, status):
        return super(cls, Status).__new__(cls, status & 1, status & 2, status & 4, status & 8, status & 16, status & 32, status & 64, status & 128)
Run Code Online (Sandbox Code Playgroud)

它运行干净,就像你预期的那样:

>>> print Status(47)
Status(started=1, checking=2, start_after_check=4, checked=8, error=0, paused=32, queued=0, loaded=0)
Run Code Online (Sandbox Code Playgroud)

  • 应该是`super(Status,cls)`! (5认同)

Ale*_*lli 10

我会避免,super除非你明确地承认多重继承(希望不是这里的情况;-).做一些像...:

def __new__(cls, status):
    return cls.__bases__[0].__new__(cls,
                                    status & 1, status & 2, status & 4,
                                    status & 8, status & 16, status & 32,
                                    status & 64, status & 128)
Run Code Online (Sandbox Code Playgroud)

  • 你还可以通过使用这个来减少代码重复:`return cls .__ bases __ [0] .__ new __(cls,*(status&(1 << x)for x in range(0,8))) (5认同)