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

2024-06-01 04:11:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个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)

现在,我在super()方面的经验是有限的,而且我在__new__方面的经验实际上是不存在的,所以我不太确定(对我来说)这个谜一般的错误是什么。通过谷歌搜索和深入研究这些文档并没有得到任何启发。

帮忙?


Tags: new标志status经验namedtuplecollectionsclasscls
2条回答

你差一点就搞定了:-)只有两个小小的修正:

  1. new方法需要一个return语句
  2. super调用应该有两个参数,clsStatus

生成的代码如下所示:

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)

它运行得很干净,正如你所料:

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

我会避免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)

相关问题 更多 >