python中如何在内部实现命名元组

python中如何在内部实现命名元组

本文介绍了python中如何在内部实现命名元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

命名元组是易于创建的轻量级对象类型.namedtuple 实例可以使用类对象变量延迟或标准元组语法来引用.如果这些数据结构可以通过对象延迟和访问索引,它们是如何在内部实现的?是通过哈希表吗?

解决方案

实际上,很容易找出给定的 namedtuple 是如何实现的:如果传递关键字参数 verbose=True 创建它时,打印它的类定义:

>>>Point = namedtuple('Point', "x y", verbose=True)从内置导入属性为 _property,元组为 _tuplefrom 运算符将 itemgetter 导入为 _itemgetter从集合导入 OrderedDict类点(元组):'点(x,y)'__slots__ = ()_fields = ('x', 'y')def __new__(_cls, x, y):'创建 Point(x, y) 的新实例'返回 _tuple.__new__(_cls, (x, y))@类方法def _make(cls, iterable, new=tuple.__new__, len=len):'从一个序列或可迭代对象中创建一个新的 Point 对象'结果 = 新(cls,可迭代)如果 len(result) != 2:raise TypeError('预期 2 个参数,得到 %d' % len(result))返回结果def _replace(_self, **kwds):'返回一个用新值替换指定字段的新 Point 对象'结果 = _self._make(map(kwds.pop, ('x', 'y'), _self))如果 kwds:raise ValueError('有意外的字段名称:%r' % list(kwds))返回结果def __repr__(self):'返回格式良好的表示字符串'返回 self.__class__.__name__ + '(x=%r, y=%r)' % self@财产def __dict__(self):'一个新的 OrderedDict 将字段名称映射到它们的值'返回 OrderedDict(zip(self._fields, self))def _asdict(self):'''返回一个新的 OrderedDict,它将字段名称映射到它们的值.这种方法已经过时了.使用 vars(nt) 或 nt.__dict__ 代替.'''返回 self.__dict__def __getnewargs__(self):'将 self 作为一个简单的元组返回.由复制和泡菜使用.返回元组(自我)def __getstate__(self):'从酸洗中排除 OrderedDict'返回无x = _property(_itemgetter(0), doc='字段编号 0 的别名')y = _property(_itemgetter(1), doc='字段编号 1 的别名')

所以,它是 tuple 的子类,带有一些额外的方法来赋予它所需的行为,一个包含字段名称的 _fields 类级常量,以及 用于访问元组成员的属性的属性方法.

至于实际构建这个类定义背后的代码,那就是深奥的魔法.

Named tuples are easy to create, lightweight object types. namedtuple instances can be referenced using object-like variable deferencing or the standard tuple syntax. If these data structures can be accessed both by object deferencing & indexes, how are they implemented internally? Is it via hash tables?

解决方案

Actually, it's very easy to find out how a given namedtuple is implemented: if you pass the keyword argument verbose=True when creating it, its class definition is printed:

>>> Point = namedtuple('Point', "x y", verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict

class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return self.__class__.__name__ + '(x=%r, y=%r)' % self

    @property
    def __dict__(self):
        'A new OrderedDict mapping field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _asdict(self):
        '''Return a new OrderedDict which maps field names to their values.
           This method is obsolete.  Use vars(nt) or nt.__dict__ instead.
        '''
        return self.__dict__

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        return None

    x = _property(_itemgetter(0), doc='Alias for field number 0')

    y = _property(_itemgetter(1), doc='Alias for field number 1')

So, it's a subclass of tuple with some extra methods to give it the required behaviour, a _fields class-level constant containing the field names, and property methods for attribute access to the tuple's members.

As for the code behind actually building this class definition, that's deep magic.

这篇关于python中如何在内部实现命名元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:55