_
で for typename を使用するコードを見ていますnamedtuple
。これは何を目的としているのだろうと思いました。
example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])
なぜ使用しないのString
ですか?
_
で for typename を使用するコードを見ていますnamedtuple
。これは何を目的としているのだろうと思いました。
example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])
なぜ使用しないのString
ですか?
これは、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')
生成されたクラスの名前が無関係であることを意味します。