2013-03-21 111 views
1

我懷疑這個問題已經被問過的類型,但我一直沒能找到它,所以這裏有雲:Python不識別namedtuple

關於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被識別爲元組類型,但它不是。任何提示?

+0

你試過'isinstance(a,tuple)'嗎? – dmg 2013-03-21 09:04:05

+0

不知道這個isinstance的東西。這將解決我的事情。謝謝! – victor 2013-03-21 09:09:49

+0

也可以用'type'來進行精確的類型匹配。 'isinstance'也處理繼承。 – dmg 2013-03-21 09:13:41

回答

12

is不檢查班級成員資格。如果is檢查兩個對象具有相同的id

>>> isinstance(a, tuple) 
True 

另外type(a)不是tupleatuple一個子類。

如果鍵入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') 

那簡直是exec被Python編。我希望能夠解決問題。

+0

很好的答案!我不能投票,因爲我剛剛創建了我的用戶。無論如何,感謝它。 – victor 2013-03-21 09:10:33

+0

@ user2194299沒問題,如果沒有人發佈任何更好的答案,您可以接受它。 – jamylak 2013-03-21 09:11:53

+1

接受的答案。 – victor 2013-03-21 09:15:58