代码之家  ›  专栏  ›  技术社区  ›  Ben Blank Jarret Hardie

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

  •  17
  • Ben Blank Jarret Hardie  · 技术社区  · 16 年前

    我想创建一个 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__ TypeError: super.__new__(Status): Status is not a subtype of super . 谷歌搜索和挖掘这些文档并没有带来任何启发。

    救命啊?

    2 回复  |  直到 16 年前
        1
  •  20
  •   Raymond Hettinger    14 年前

    你差一点就成功了:-)这里有两个小小的修正:

    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)
    

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

    >>> print Status(47)
    Status(started=1, checking=2, start_after_check=4, checked=8, error=0, paused=32, queued=0, loaded=0)
    
        2
  •  10
  •   Alex Martelli    16 年前

    我会避免 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)
    
    推荐文章