python – 在namedtuple中使用’_’作为typename做了什么特别的事吗?

weixin_38055888 2019-09-12 10:36:52
我正在查看在namedtuple中使用_作为typename的代码.我想知道这是什么目的. example = namedtuple('_', ['NameOfClass1', 'NameOfClass2']) 为什么不使用String?
...全文
58 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38069804 2019-09-12
  • 打赏
  • 举报
回复
这是一个有点奇怪的例子.重点是为类及其属性提供有意义的名称.诸如__repr__和类docstring之类的一些功能从有意义的名称中获得了大部分好处. FWIW,namedtuple工厂包括一个详细的选项,可以很容易地理解工厂对其输入做了什么.当verbose = True时,工厂打印出它创建的类定义: >>> from collections import namedtuple >>> example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'], verbose=True) class _(tuple): '_(NameOfClass1, NameOfClass2)' __slots__ = () _fields = ('NameOfClass1', 'NameOfClass2') def __new__(_cls, NameOfClass1, NameOfClass2): 'Create new instance of _(NameOfClass1, NameOfClass2)' return _tuple.__new__(_cls, (NameOfClass1, NameOfClass2)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new _ 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 __repr__(self): 'Return a nicely formatted representation string' return '_(NameOfClass1=%r, NameOfClass2=%r)' % 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 _ object replacing specified fields with new values' result = _self._make(map(kwds.pop, ('NameOfClass1', 'NameOfClass2'), _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) NameOfClass1 = _property(_itemgetter(0), doc='Alias for field number 0') NameOfClass2 = _property(_itemgetter(1), doc='Alias for field number 1')

473

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧