通过子类化修改命名元组的构造函数参数?
我想创建一个 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
的含义。谷歌搜索和深入研究文档并没有产生任何启发性的东西。
帮助?
I want to create a namedtuple
which represents the individual flags in a short bitfield. I'm trying to subclass it so that I can unpack the bitfield before the tuple is created. However, my current attempt isn't working:
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)
Now, my experience with super()
is limited and my experience with __new__
is virtually non-existent, so I'm not quite sure what to make of the (to me) enigmatic error TypeError: super.__new__(Status): Status is not a subtype of super
. Googling and digging into the docs haven't yielded anything enlightening.
Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你几乎已经成功了 :-) 只有两个小修正:
结果代码如下所示:
它运行干净,就像您所期望的那样:
You almost had it :-) There are just two little corrections:
The resulting code looks like this:
It runs cleanly, just like you had expected:
我会避免使用
super
除非你明确地迎合多重继承(希望不是这里的情况;-)。只需做一些像...:I'd avoid
super
unless you're explicitly catering to multiple inheritance (hopefully not the case here;-). Just do something like...: