python namedtuple函数的使用

作者:一撸程猿 时间:2021-09-27 08:18:30 

目录
  • 先看演示

    • 像类一样的访问属性

    • 类似字典的访问

    • 为什么可以这样?

  • 源码解析

    • 为什么有类的影子?

    • 为什么有字典的影子?

先看演示

像类一样的访问属性


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))

来源:https://juejin.cn/post/6973302732740362277

标签:python,namedtuple
0
投稿

猜你喜欢

  • 如何使用图片精灵优化你的网站

    2009-07-21 11:35:00
  • Pycharm生成可执行文件.exe的实现方法

    2023-07-19 12:09:54
  • Python实现FTP文件定时自动下载的步骤

    2022-04-13 02:07:14
  • Python解析json文件相关知识学习

    2022-04-01 12:58:19
  • python编程matplotlib交互绘制Julia集示例解析

    2021-07-31 17:14:45
  • Python+unittest+requests+excel实现接口自动化测试框架

    2021-09-08 07:04:49
  • 详解Python常用标准库之os模块与shutil模块

    2023-06-13 04:19:20
  • 小议sqlserver数据库主键选取策略

    2011-10-24 19:51:30
  • JS二维数组的定义说明

    2023-08-23 15:09:45
  • 网页打开速度的心理学

    2009-03-26 13:18:00
  • 利用Python通过获取剪切板数据实现百度划词搜索功能

    2023-07-14 06:59:06
  • Python scikit-learn 做线性回归的示例代码

    2022-05-03 11:00:54
  • 在pycharm中使用git版本管理以及同步github的方法

    2021-12-08 01:59:58
  • Python实现字符串与数组相互转换功能示例

    2021-08-13 15:50:12
  • 实例讲解PHP验证邮箱是否合格

    2023-11-22 07:05:53
  • Tensorflow矩阵运算实例(矩阵相乘,点乘,行/列累加)

    2023-12-19 04:07:42
  • 浅谈python import引入不同路径下的模块

    2022-03-12 14:21:38
  • Python爬取商家联系电话以及各种数据的方法

    2023-07-24 18:39:38
  • Python标准库与第三方库详解

    2021-12-16 04:23:03
  • LotusPhp笔记之:基于ObjectUtil组件的使用分析

    2023-11-19 09:18:32
  • asp之家 网络编程 m.aspxhome.com