Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从namedtuple子类化_Python_Python 3.x - Fatal编程技术网

Python 从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,

我使用的是Python3.6,在从namedtuple生成子类时遇到了一个问题。例如:

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