Python中namedtuple具名元组的简单使用

参考链接: Python namedtuple
参考链接: namedtuple() 命名元组的工厂函数

一下内容摘自菜鸟教程runoob.com:

Python元组的升级版本 -- namedtuple(具名元组)

因为元组的局限性:不能为元组内部的数据进行命名,
所以往往我们并不知道一个元组所要表达的意义,
所以在这里引入了 collections.namedtuple 这个工厂函数,
来构造一个带字段名的元组。具名元组的实例和普通元组消耗的内存一样多,
因为字段名都被存在对应的类里面。
这个类跟普通的对象实例比起来也要小一些,
因为 Python 不会用 __dict__ 来存放这些实例的属性。
namedtuple 对象的定义如以下格式:
collections.namedtuple(typename, field_names, verbose=False, rename=False) 

collections.namedtuple(typename, field_names, verbose=False, rename=False)

  • 返回一个具名元组子类 typename,其中参数的意义如下:
    • typename:元组名称
    • field_names: 元组中元素的名称
    • rename: 如果元素名称中含有 python 的关键字,则必须设置为 rename=True
    • verbose: 默认就好

collections.namedtuple('User', 'name age id') 创建一个具名元组, 需要两个参数,一个是类名,另一个是类的各个字段名。 后者可以是有多个字符串组成的可迭代对象, 或者是有空格分隔开的字段名组成的字符串(比如本示例)。 具名元组可以通过字段名或者位置来获取一个字段的信息。

类属性 _fields:包含这个类所有字段名的元组 
 类方法 _make(iterable):接受一个可迭代对象来生产这个类的实例 
 实例方法 _asdict():把具名元组以 collections.OrdereDict 的形式返回,
 可以利用它来把元组里的信息友好的展示出来。

实验演示1:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import collections
>>> from collections import namedtuple
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0]
11
>>> p[1]
22
>>> p.x
11
>>> p.y
22
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
>>> 
>>> # 从存在的序列或迭代实例创建一个新实例。
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
>>> 
>>> 
>>> 
>>> # Return a new OrderedDict which maps field names to their corresponding values:
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])
>>> 
>>> 
>>> p
Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)
>>> p
Point(x=11, y=22)
>>> 
>>> 
>>> p._fields            # view the field names
('x', 'y')
>>> 
>>> getattr(p, 'x') # 获取这个名字域的值,使用 getattr() 函数 :
11
>>> 
>>> 
>>> Color = namedtuple('Color', 'red green blue')
>>> p._fields            # view the field names
('x', 'y')
>>> Color._fields
('red', 'green', 'blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel._fields
('x', 'y', 'red', 'green', 'blue')
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
>>> 
>>> 

实验演示2:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import collections
>>> from collections import namedtuple
>>> # 两种方法来给 namedtuple 定义方法名
>>> # User = collections.namedtuple('User', ['name', 'age', 'id'])
>>> # User = collections.namedtuple('User', 'name age id')
>>> Person = collections.namedtuple('Friend4cxq', 'name age id')
>>> p = Person('tester', '22', '464643123')
>>> p
Friend4cxq(name='tester', age='22', id='464643123')
>>> Friend4cxq = Person
>>> p = Friend4cxq('昊昊', '55', '123')
>>> p
Friend4cxq(name='昊昊', age='55', id='123')
>>> 
>>> 
>>> 
>>> 
>>> Friend4cxq = collections.namedtuple('Friend4cxq', ['name', 'age', 'gender'])
>>> hh = Friend4cxq('haohao',33,'male')
>>> hh
Friend4cxq(name='haohao', age=33, gender='male')
>>> print(hh)
Friend4cxq(name='haohao', age=33, gender='male')
>>> 
>>> yzb = Friend4cxq(name='宝儿', age=88, gender='男')
>>> yzb
Friend4cxq(name='宝儿', age=88, gender='男')
>>> 
>>> 
>>> # 获取所有字段名
>>> print( yzb._fields )
('name', 'age', 'gender')
>>> 
>>> 
>>> # 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法
>>> cjh = Friend4cxq._make(['金涵', 12,'男子'])
>>> cjh
Friend4cxq(name='金涵', age=12, gender='男子')
>>> cjh.name
'金涵'
>>> cjh.age
12
>>> cjh.gender
'男子'
>>> # 以上用于获取用户的属性
>>> 
>>> 
>>> # 修改对象属性,注意要使用"_replace"方法
>>> cjh._replace(gender='男性')
Friend4cxq(name='金涵', age=12, gender='男性')
>>> cjh
Friend4cxq(name='金涵', age=12, gender='男子')
>>> cjh = cjh._replace(gender='男性')
>>> cjh
Friend4cxq(name='金涵', age=12, gender='男性')
>>> 
>>> 
>>> 
>>> 
>>> 
>>> # 将User对象转换成字典,注意要使用"_asdict"
>>> print( cjh._asdict() )
OrderedDict([('name', '金涵'), ('age', 12), ('gender', '男性')])
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值