Python namedtuple使用详解

栏目: Python · 发布时间: 9年前

内容简介:Python namedtuple使用详解

@author StormMa

@date 2017-06-12

生命不息,奋斗不止!

Python的collections模块在基础数据类型的基础上,提供了几个额外的数据类型:namedtuple, defaultdict, deque, Counter, OrderedDict等,其中defaultdict和namedtuple是两个很实用的扩展类型。我一贯的风格就是学一个数据类型,就想去看看源码,虽然看不太懂,但是总比不看的强,之前 java 的集合源码阅读也是基于这样一个目的。今天就从使用和源码的角度来看一下namedtuple。

namedtuple是继承自tuple的子类。namedtuple创建一个和tuple类似的对象,而且对象拥有可访问的属性。

定义namedtuple

类的声明

class NamedTuple(tuple):
    _fields = ...  # type: Tuple[str, ...]

    def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]], *,
                 verbose: bool = ..., rename: bool = ..., module: Any = ...) -> None: ...

    @classmethod
    def _make(cls, iterable: Iterable[Any]) -> NamedTuple: ...

    def _asdict(self) -> dict: ...
    def _replace(self, **kwargs: Any) -> NamedTuple: ...

定义一个namedtuple的User类型

User = collections.namedtuple('User', ['age', 'name'])
或者
User = collections.namedtuple('User', 'age, name')
或者
User = collections.namedtuple('User', 'age name')

对应源码

def namedtuple(typename, field_names, verbose=False, rename=False):
    """Returns a new subclass of tuple with named fields.

    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessable by name
    33
    >>> d = p._asdict()                 # convert to a dictionary
    >>> d['x']
    11
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)
    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
    Point(x=100, y=22)

    """

    # Validate the field names.  At the user's option, either generate an error
    # message or automatically replace the field name with a valid name.
    if isinstance(field_names, str):
        field_names = field_names.replace(',', ' ').split()
    field_names = list(map(str, field_names))

创建对象

user = User = (21, 'StormMa')
或者
user = User(age=21, name='StormMa')
或者
user = User._make([21, 'name'])

属性访问

# 年龄
user.age

# 姓名
user.name

转换成字典

user_dict = user._asdict()

# 访问 
user_dict['name']
user_dict['age']

替换属性值

user2 = user._replace(age=20)

本文来自我的个人站点: http://blog.stormma.me ,转载请注明出处!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

社交天性

社交天性

[美] 马修·利伯曼(Matthew D. Lieberman) / 贾拥民 / 浙江人民出版社 / 2016-6 / 69.90

[内容简介] ● 《社交天性》是社会心理学家马修·利伯曼解读人类“社会脑”的权威之作,它告诉我们为什么在充满合作与竞争的智慧社会中人们喜爱社交又相互连接,个人的社会影响力如何得以发挥,书中处处充满了令人惊喜的洞见。 ● 为什么有的人天生善于社交,而有的人总是充满障碍? 为什么智商越高的人越难相处? 心痛对人的伤害甚至超过头痛? 慈善组织如何激发人们的捐赠行为? ......一起来看看 《社交天性》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具