python - 在 namedtuple 中使用 '_' 作为 typename 有什么特别之处吗?

标签 python collections tuples namedtuple

我正在查看确实在 namedtuple 中使用 _ 作为类型名称的代码。我想知道这样做的目的是什么。

example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])

为什么不直接使用 String

最佳答案

这是一个有点奇怪的命名元组的例子。重点是为类及其属性赋予有意义的名称。 __repr__ 和类文档字符串等一些功能的大部分优势都来自有意义的名称。

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

关于python - 在 namedtuple 中使用 '_' 作为 typename 有什么特别之处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923493/

相关文章:

python - Cython调用lapack,报错: `Cannot take address of Python variable'

python - 打印元组中的每 2 个元素

python - 如何访问二维列表中的元组

python - 我单独打印一个元组,但不与其他变量一起打印

python - 如何在子类 python 枚举上抑制 "index should be a string"类型错误

python - 什么{:02d} mean in Python

python - 如何打印 python 数组中的列?

java - 将子类型集合分配给父类型

java - 有什么方法可以流式传输像 "(k,v)"这样的 map 而不是使用(条目)?

c# - 存储父子关系