主頁 > 知識庫 > python namedtuple函數(shù)的使用

python namedtuple函數(shù)的使用

熱門標簽:聊城語音外呼系統(tǒng) 騰訊地圖標注沒法顯示 南陽打電話機器人 地圖標注自己和別人標注區(qū)別 打電話機器人營銷 ai電銷機器人的優(yōu)勢 海外網(wǎng)吧地圖標注注冊 商家地圖標注海報 孝感營銷電話機器人效果怎么樣

先看演示

像類一樣的訪問屬性

from collections import namedtuple

Friend = 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)
RidingRoad
male
Mars
The five-star high praise
Change the world by Program!
Do what you like!
Live what you want!

類似字典的訪問

像字典一樣訪問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!')
******************************
RidingRoad
male
Mars
The five-star high praise
Change the world by Program!
Do what you like!
Live what you want!

為什么可以這樣?

到這里,你應(yīng)該會有兩個疑問:

  1. 為什么有類的影子?
  2. 為什么有字典的影子?

源碼解析

為什么有類的影子?

看源碼的_class_template部分,其實函數(shù)內(nèi)部為我們創(chuàng)了一個類了

# 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干了什么?對類進行定義

_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部分,這里封裝成了有序字典,所以我們可以通過__dict__訪問字典的特性了

__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ù)的使用的詳細內(nèi)容,更多關(guān)于python namedtuple函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!

您可能感興趣的文章:
  • python中把元組轉(zhuǎn)換為namedtuple方法
  • 詳解Python中namedtuple的使用
  • Python namedtuple命名元組實現(xiàn)過程解析
  • Python的collections模塊中namedtuple結(jié)構(gòu)使用示例
  • 簡單講解Python編程中namedtuple類的用法
  • Python中的defaultdict模塊和namedtuple模塊的簡單入門指南

標簽:迪慶 牡丹江 撫州 南寧 六盤水 聊城 揚州 楊凌

巨人網(wǎng)絡(luò)通訊聲明:本文標題《python namedtuple函數(shù)的使用》,本文關(guān)鍵詞  python,namedtuple,函數(shù),的,使用,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《python namedtuple函數(shù)的使用》相關(guān)的同類信息!
  • 本頁收集關(guān)于python namedtuple函數(shù)的使用的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章