栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

实际上,很容易找出给定

namedtuple
的实现方式:如果
verbose=True
在创建给定参数时传递了关键字参数,则会打印其类定义:

>>> Point = namedtuple('Point', "x y", verbose=True)from builtins import property as _property, tuple as _tuplefrom operator import itemgetter as _itemgetterfrom collections import OrderedDictclass 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
用于访问元组成员的属性的方法。

至于实际建立该类定义的代码,那真是
不可思议




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646916.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号