Python不识别命名元组的类型

4 投票
1 回答
5084 浏览
提问于 2025-04-17 19:51

我怀疑这个问题之前有人问过,但我找不到相关内容,所以我就问了:

在Python(使用2.7版本)中,我创建了一个namedtuple,代码如下:

>>> sgn_tuple = namedtuple('sgnt',['signal','type'])
>>> a = sgn_tuple("aaa","bbb")

然后我想检查一下t的类型,结果却很奇怪:

>>> type (a)
<class '__main__.sgnt'>
>>> a is tuple
False
>>> a is namedtuple
False
>>> a is sgnt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sgnt' is not defined
>>> a is sgn_tuple
False
>>>

这是为什么呢?我本以为a会被识别为元组类型,但实际上并不是。有没有什么提示?

1 个回答

15

is 这个东西并不是用来检查一个对象是不是某个类的成员。它其实是用来检查两个对象是不是同一个东西,也就是它们的 id 是否相同。

>>> isinstance(a, tuple)
True

另外,type(a) 不是 tuple,而是 atuple 的一个子类。

如果你输入 verbose=True,你可以看到它是怎么生成的(这些文本是动态生成的,用来创建这个类):

>>> sgn_tuple = namedtuple('sgnt',['signal','type'],verbose=True)

class sgnt(tuple):
        'sgnt(signal, type)' 

        __slots__ = () 

        _fields = ('signal', 'type') 

        def __new__(_cls, signal, type):
            'Create new instance of sgnt(signal, type)'
            return _tuple.__new__(_cls, (signal, type)) 

        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new sgnt object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != 2:
                raise TypeError('Expected 2 arguments, got %d' % len(result))
            return result 

        def __repr__(self):
            'Return a nicely formatted representation string'
            return 'sgnt(signal=%r, type=%r)' % self 

        def _asdict(self):
            'Return a new OrderedDict which maps field names to their values'
            return OrderedDict(zip(self._fields, self)) 

        __dict__ = property(_asdict) 

        def _replace(_self, **kwds):
            'Return a new sgnt object replacing specified fields with new values'
            result = _self._make(map(kwds.pop, ('signal', 'type'), _self))
            if kwds:
                raise ValueError('Got unexpected field names: %r' % kwds.keys())
            return result 

        def __getnewargs__(self):
            'Return self as a plain tuple.  Used by copy and pickle.'
            return tuple(self) 

        signal = _property(_itemgetter(0), doc='Alias for field number 0')
        type = _property(_itemgetter(1), doc='Alias for field number 1')

这其实就是被 Python 执行的。我希望这样能让你更明白。

撰写回答