I was learning the python. And when comes to the collection module in official library, I found a code snipet of the NamedTuple like:
for i, name in enumerate(field_names):
template += " %s = _property(_itemgetter(%d), doc='Alias for field number %d')\n" % (name, i, i)
And it's one part of the code that generated by the NamedTuple. The code generated is listed below:
name = property(itemgetter(0), doc='Alias for field number 0')
age = property(itemgetter(1), doc='Alias for field number 1')
And here is my question:
Itemgetter(0) is a function which needs an object as arguments. But property will not pass any arguments to the itemgetter. So how does this work?
Thank you!
This is the whole code that property is used:
class Person(tuple):
'Person(name, age)'
__slots__ = ()
_fields = ('name', 'age')
def __new__(_cls, name, age):
'Create new instance of Person(name, age)'
print sys._getframe().f_code.co_name
return _tuple.__new__(_cls, (name, age))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Person object from a sequence or iterable'
print sys._getframe().f_code.co_name
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'
print sys._getframe().f_code.co_name
return 'Person(name=%r, age=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
print sys._getframe().f_code.co_name
return OrderedDict(zip(self._fields, self))
def _replace(_self, **kwds):
'Return a new Person object replacing specified fields with new values'
print sys._getframe().f_code.co_name
result = _self._make(map(kwds.pop, ('name', 'age'), _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.'
print sys._getframe().f_code.co_name
return tuple(self)
name = property(itemgetter(0), doc='Alias for field number 0')
age = property(itemgetter(1), doc='Alias for field number 1')