gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:00:20 27 4
gpt4 key购买 nike

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

最佳答案

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

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

因此,它是 tuple 的子类,具有一些额外的方法来为其提供所需的行为,一个包含字段名称的 _fields 类级常量,以及 property 方法,用于对元组成员进行属性访问。

至于实际构建此类定义的代码,那是 deep magic .

关于python - 命名元组如何在 python 内部实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17916853/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com