我正在学习python。当谈到官方库中的集合模块时,我发现了 NamedTuple 的代码片段,例如:
for i, name in enumerate(field_names):
template += " %s = _property(_itemgetter(%d), doc='Alias for field number %d')\n" % (name, i, i)
它是 NamedTuple 生成的代码的一部分。生成的代码如下:
name = property(itemgetter(0), doc='Alias for field number 0')
age = property(itemgetter(1), doc='Alias for field number 1')
这是我的问题:
Itemgetter(0) 是一个需要对象作为参数的函数。但是属性不会将任何参数传递给 itemgetter。那么这是如何工作的呢?
谢谢!
这是使用该属性的全部代码:
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')