python namedtuple函數(shù)的使用
from collections import namedtupleFriend = namedtuple(’Friend’, [’name’, ’gender’, ’address’, ’star’, ’signature’])RidingRoad = Friend(’RidingRoad’, ’male’, ’Mars’, ’The five-star high praise’, ’Change the world by Program!n’ ’Do what you like!n’ ’Live what you want!’)print(RidingRoad.name)print(RidingRoad.gender)print(RidingRoad.address)print(RidingRoad.star)print(RidingRoad.signature)
RidingRoadmaleMarsThe five-star high praiseChange the world by Program!Do what you like!Live what you want!類(lèi)似字典的訪(fǎng)問(wèn)
像字典一樣訪(fǎng)問(wèn)items、keys、values
for key, value in RidingRoad.__dict__.items(): print(key, value)print('*' * 30)for key in RidingRoad.__dict__.keys(): print(’{}: ’.format(key), eval(’RidingRoad.{}’.format(key)))print('*' * 30)for value in RidingRoad.__dict__.values(): print(value)
(’name’, ’RidingRoad’)(’gender’, ’male’)(’address’, ’Mars’)(’star’, ’The five-star high praise’)(’signature’, ’Change the world by Program!nDo what you like!nLive what you want!’)******************************(’name: ’, ’RidingRoad’)(’gender: ’, ’male’)(’address: ’, ’Mars’)(’star: ’, ’The five-star high praise’)(’signature: ’, ’Change the world by Program!nDo what you like!nLive what you want!’)******************************RidingRoadmaleMarsThe five-star high praiseChange the world by Program!Do what you like!Live what you want!為什么可以這樣?
到這里,你應(yīng)該會(huì)有兩個(gè)疑問(wèn):
為什么有類(lèi)的影子? 為什么有字典的影子? 源碼解析為什么有類(lèi)的影子?看源碼的_class_template部分,其實(shí)函數(shù)內(nèi)部為我們創(chuàng)了一個(gè)類(lèi)了
# Fill-in the class template class_definition = _class_template.format(typename = typename,field_names = tuple(field_names),num_fields = len(field_names),arg_list = repr(tuple(field_names)).replace('’', '')[1:-1],repr_fmt = ’, ’.join(_repr_template.format(name=name) for name in field_names),field_defs = ’n’.join(_field_template.format(index=index, name=name) for index, name in enumerate(field_names)) ) if verbose:print class_definition
然后_class_template干了什么?對(duì)類(lèi)進(jìn)行定義
_class_template = ’’’class {typename}(tuple): ’{typename}({arg_list})’ __slots__ = () _fields = {field_names!r} def __new__(_cls, {arg_list}):’Create new instance of {typename}({arg_list})’return _tuple.__new__(_cls, ({arg_list})) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len):’Make a new {typename} object from a sequence or iterable’result = new(cls, iterable)if len(result) != {num_fields:d}: raise TypeError(’Expected {num_fields:d} arguments, got %d’ % len(result))return result def __repr__(self):’Return a nicely formatted representation string’return ’{typename}({repr_fmt})’ % self def _asdict(self):’Return a new OrderedDict which maps field names to their values’return OrderedDict(zip(self._fields, self)) def _replace(_self, **kwds):’Return a new {typename} object replacing specified fields with new values’result = _self._make(map(kwds.pop, {field_names!r}, _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) __dict__ = _property(_asdict) def __getstate__(self):’Exclude the OrderedDict from pickling’pass{field_defs}’’’為什么有字典的影子?
看源碼的 _asdict部分,這里封裝成了有序字典,所以我們可以通過(guò)__dict__訪(fǎng)問(wèn)字典的特性了
__dict__ = _property(_asdict) def _asdict(self):’Return a new OrderedDict which maps field names to their values’return OrderedDict(zip(self._fields, self))
以上就是python namedtuple函數(shù)的使用的詳細(xì)內(nèi)容,更多關(guān)于python namedtuple函數(shù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. XML入門(mén)的常見(jiàn)問(wèn)題(四)2. HTML5 Canvas繪制圖形從入門(mén)到精通3. ASP基礎(chǔ)知識(shí)VBScript基本元素講解4. 利用CSS3新特性創(chuàng)建透明邊框三角5. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼6. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. JSP的Cookie在登錄中的使用9. XHTML 1.0:標(biāo)記新的開(kāi)端10. PHP設(shè)計(jì)模式中工廠(chǎng)模式深入詳解
