Использует ли '_' для typename в именованном корте ничего особенного? - PullRequest
3 голосов
/ 28 октября 2011

Я смотрю на код, который использует _ для typename в namedtuple. Мне было интересно, какова цель этого.

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

Почему бы просто не использовать String?

Ответы [ 2 ]

4 голосов
/ 30 ноября 2011

Это несколько странный пример namedtuple .Весь смысл в том, чтобы дать значимые имена классу и его атрибутам.Некоторые функции, такие как __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')
1 голос
/ 28 октября 2011

Просто означает, что имя сгенерированного класса не имеет значения.

...