Python 从namedtuple子类化
我使用的是Python3.6,在从namedtuple生成子类时遇到了一个问题。例如:Python 从namedtuple子类化,python,python-3.x,Python,Python 3.x,我使用的是Python3.6,在从namedtuple生成子类时遇到了一个问题。例如: from collections import namedtuple FieldMetaInfoBase = namedtuple('FieldMetaInfoBase', ['name', 'type', 'special']) class FieldMetaInfo(FieldMetaInfoBase): def __init__(self, name,
from collections import namedtuple
FieldMetaInfoBase = namedtuple('FieldMetaInfoBase', ['name', 'type', 'special'])
class FieldMetaInfo(FieldMetaInfoBase):
def __init__(self,
name,
type,
special):
# throws TypeError: object.__init__() takes no parameters
super(FieldMetaInfo, self).__init__(name, type, special)
# is this correct??
# FieldMetaInfoBase.__init__(name, type, special)
fmi = FieldMetaInfo('a', 'b', 'c')
由于某些原因,我无法使用某些值初始化元组,因为我遇到了一个错误:
TypeError: object.__init__() takes no parameters
有人知道如何解决这个问题吗?还是我的解决方案正确
FieldMetaInfoBase.__init__(name, type, special)
Namedtuples是可修改的,因此您需要使用
\uuuuu new\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
在Python3.x中,您可以使用self=super()。\uuuuu new\uuuuu(cls、name、type、special)
(尽管本答案中显示的长格式也适用)。无论如何,您应该添加一个\uuu slots\uu=()
类属性,以防止在派生类中创建\uuu dict\uuu
。
class FieldMetaInfo(FieldMetaInfoBase):
def __new__(cls, name, type, special):
self = super(FieldMetaInfo, cls).__new__(cls, name, type, special)
return self