主页 > 知识库 > python namedtuple函数的使用

python namedtuple函数的使用

热门标签:聊城语音外呼系统 腾讯地图标注没法显示 南阳打电话机器人 地图标注自己和别人标注区别 打电话机器人营销 ai电销机器人的优势 海外网吧地图标注注册 商家地图标注海报 孝感营销电话机器人效果怎么样

先看演示

像类一样的访问属性

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!

为什么可以这样?

到这里,你应该会有两个疑问:

  1. 为什么有类的影子?
  2. 为什么有字典的影子?

源码解析

为什么有类的影子?

看源码的_class_template部分,其实函数内部为我们创了一个类了

# 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函数的使用的详细内容,更多关于python namedtuple函数的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
  • python中把元组转换为namedtuple方法
  • 详解Python中namedtuple的使用
  • Python namedtuple命名元组实现过程解析
  • Python的collections模块中namedtuple结构使用示例
  • 简单讲解Python编程中namedtuple类的用法
  • Python中的defaultdict模块和namedtuple模块的简单入门指南

标签:迪庆 牡丹江 抚州 南宁 六盘水 聊城 扬州 杨凌

巨人网络通讯声明:本文标题《python namedtuple函数的使用》,本文关键词  python,namedtuple,函数,的,使用,;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 下面列出与本文章《python namedtuple函数的使用》相关的同类信息!
  • 本页收集关于python namedtuple函数的使用的相关信息资讯供网民参考!
  • 推荐文章