7
命名元組很容易創建,輕量級對象類型。可以使用類似於對象的變量引用或標準元組語法來引用namedtuple
實例。如果這些數據結構可以通過對象引用&索引來訪問,那麼它們是如何在內部實現的?它是通過哈希表嗎?命名元組是如何在python內部實現的?
命名元組很容易創建,輕量級對象類型。可以使用類似於對象的變量引用或標準元組語法來引用namedtuple
實例。如果這些數據結構可以通過對象引用&索引來訪問,那麼它們是如何在內部實現的?它是通過哈希表嗎?命名元組是如何在python內部實現的?
其實,這是很容易找出如何在給定namedtuple
實現:如果您在創建時,它通過關鍵字參數verbose=True
,其類定義打印:
>>> Point = namedtuple('Point', "x y", verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class Point(tuple):
'Point(x, y)'
__slots__ =()
_fields = ('x', 'y')
def __new__(_cls, x, y):
'Create new instance of Point(x, y)'
return _tuple.__new__(_cls, (x, y))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Point 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 _replace(_self, **kwds):
'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(x=%r, y=%r)' % self
@property
def __dict__(self):
'A new OrderedDict mapping field names to their values'
return OrderedDict(zip(self._fields, self))
def _asdict(self):
'''Return a new OrderedDict which maps field names to their values.
This method is obsolete. Use vars(nt) or nt.__dict__ instead.
'''
return self.__dict__
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
return None
x = _property(_itemgetter(0), doc='Alias for field number 0')
y = _property(_itemgetter(1), doc='Alias for field number 1')
因此,它的tuple
一個子類用一些額外的方法賦予它所需的行爲,包含字段名稱的_fields
類級常量,以及用於對元組成員進行屬性訪問的方法。
至於實際構建這個類定義的代碼,那是deep magic。
檢查此鏈接。這可能會幫助你。 (http://stackoverflow.com/questions/9872255/when-and-why-should-i-use-a-namedtuple-instead-of-a-dictionary) –