Python namedtuple详解:类属性与字典访问的双重特性
本文深入解析Python中namedtuple的使用方法及底层原理。通过演示如何像类一样访问属性以及像字典一样获取items、keys和values,揭示其双重特性。结合源码分析_class_template和_asdict方法,解释namedtuple如何继承tuple并封装为有序字典,帮助开发者全面掌握这一高效数据结构。
首先通过代码演示来直观了解namedtuple的基本用法。
namedtuple实例支持类似类的属性访问方式,可以直接通过点号获取字段值。
from collections import namedtuple
Friend = namedtuple('Friend', ['name', 'gender', 'address', 'star', 'signature'])
RidingRoad = Friend('RidingRoad', 'male', 'Mars', 'The five-star high praise',
'Change the world by Program!\n'
'Do what you like!\n'
'Live what you want!')
print(RidingRoad.name)
print(RidingRoad.gender)
print(RidingRoad.address)
print(RidingRoad.star)
print(RidingRoad.signature)
RidingRoad male Mars The five-star high praise Change the world by Program! Do what you like! Live what you want!
除了类式访问,它还提供类似字典的访问接口,方便进行键值对操作。
可以通过__dict__属性像字典一样遍历items、keys和values,实现灵活的数据提取。
for key, value in RidingRoad.__dict__.items():
print(key, value)
print("*" * 30)
for key in RidingRoad.__dict__.keys():
print('{}: '.format(key), eval('RidingRoad.{}'.format(key)))
print("*" * 30)
for value in RidingRoad.__dict__.values():
print(value)
('name', 'RidingRoad')
('gender', 'male')
('address', 'Mars')
('star', 'The five-star high praise')
('signature', 'Change the world by Program!\nDo what you like!\nLive what you want!')
******************************
('name: ', 'RidingRoad')
('gender: ', 'male')
('address: ', 'Mars')
('star: ', 'The five-star high praise')
('signature: ', 'Change the world by Program!\nDo what you like!\nLive what you want!')
******************************
RidingRoad
male
Mars
The five-star high praise
Change the world by Program!
Do what you like!
Live what you want!
了解具体用法后,接下来探讨其背后的实现机制。
在阅读源码前,读者可能会产生两个核心疑问:
- 为什么namedtuple看起来具有类的特征?
- 为什么它又能表现出字典的行为?
为了解答上述疑问,我们需要深入分析Python标准库中的源码实现。
关于类特征的来源,关键在于源码中的_class_template部分。
namedtuple函数内部实际上动态创建了一个新的类,该类继承自tuple。
# Fill-in the class template
class_definition = _class_template.format(
typename = typename,
field_names = tuple(field_names),
num_fields = len(field_names),
arg_list = repr(tuple(field_names)).replace("'", "")[1:-1],
repr_fmt = ', '.join(_repr_template.format(name=name)
for name in field_names),
field_defs = '\n'.join(_field_template.format(index=index, name=name)
for index, name in enumerate(field_names))
)
if verbose:
print class_definition
_class_template的主要作用是对这个动态生成的类进行完整定义,包括初始化、表示方法和字段定义。
_class_template = '''\
class {typename}(tuple):
'{typename}({arg_list})'
__slots__ = ()
_fields = {field_names!r}
def __new__(_cls, {arg_list}):
'Create new instance of {typename}({arg_list})'
return _tuple.__new__(_cls, ({arg_list}))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new {typename} object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != {num_fields:d}:
raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return '{typename}({repr_fmt})' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
def _replace(_self, **kwds):
'Return a new {typename} object replacing specified fields with new values'
result = _self._make(map(kwds.pop, {field_names!r}, _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
__dict__ = _property(_asdict)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
pass
{field_defs}
'''
关于字典特征的来源,主要涉及_asdict方法的实现逻辑。
查看源码中的_asdict部分,可以看到它返回一个有序字典(OrderedDict),这使得我们可以通过__dict__属性访问字典特有的功能。
__dict__ = _property(_asdict)
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
以上是对Python namedtuple函数使用及原理的完整解析,更多相关技术资料欢迎持续关注本站后续更新。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









