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 ,转载请注明出处!


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

查看所有标签

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

Alone Together

Alone Together

Sherry Turkle / Basic Books / 2011-1-11 / USD 28.95

Consider Facebookit’s human contact, only easier to engage with and easier to avoid. Developing technology promises closeness. Sometimes it delivers, but much of our modern life leaves us less connect......一起来看看 《Alone Together》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具