私はnamedtuple
のtypenameに_
を使用するコードを見ています。私はこれの目的が何か不思議だった。名前付きタプルのtypenameに '_'を使用すると、特別な処理が行われますか?
String
を使用しないのはなぜですか。
私はnamedtuple
のtypenameに_
を使用するコードを見ています。私はこれの目的が何か不思議だった。名前付きタプルのtypenameに '_'を使用すると、特別な処理が行われますか?
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')
ちょうど生成されたクラスの名前は無関係であることを意味しています。
なぜ使用 '「String''だけではなく、'」_''? ;)両方とも同様に有効な識別子です。 – delnan
FWIWでは、 "_"はプログラマによって未使用のスローアウェイ変数名でよく使用されます。 –