2007年01月31日 星期三 14:39
ÒÔÏÂÊÇÎÒ´ÓÀý³ÌÖÐժ¼µÄÒ»¸ö·½·¨£º def NamedTuple(s): """Returns a new subclass of tuple with named fields. >>> Point = NamedTuple('Point x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # works just like the tuple (11, 22) 33 >>> p.x + p.y # fields also accessable by name 33 >>> p # readable __repr__ with name=value style Point(x=11, y=22) """ f = s.split() typename, field_names = f[0], f[1:] nargs = len(field_names) def __new__(cls, *args, **kwds): if kwds: try: args += tuple(kwds[name] for name in field_names[len(args):]) except KeyError, name: raise TypeError('%s missing required argument: %s' % (typename, name)) if len(args) != nargs: raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, nargs, len(args))) return tuple.__new__(cls, args) template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name infield_names)) def __repr__(self, show=template.__mod__): return show(self) m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup) m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)), __slots__ = (), # no per-instance dict (so instances are same size as tuples) __new__ = __new__, __repr__ = __repr__, ) m.update((name, property(itemgetter(index))) for index, name inenumerate(field_names)) return type(typename, (tuple,), m) ÎÒ¶ÔÆäÖм¸¸ö²¿·Ö²»¶®£º 1 ÔÚ·½·¨NamedTuple(s)Öж¨Òå__new__()ºÍ__repar__()ÊÇÖØÔØô£¿Èç¹ûÊÇ£¬ÖØÔز»ÐèÒªÔÚÀàÖнøÐÐô£¿ 2 __new__()ºÍ__repar__()¸÷×ÔÔÚʲôʱºò±»µ÷Óã¿ 3 ÓкܶàµÄ__slots__ £¬__new__£¬ __repr__ϵͳ±äÁ¿£¬ÕâЩ±äÁ¿¸ÄÔõôÀ´Á˽âËûÃǵÄÓÃ;ô£¿ ѧϰing -------------- 下一部分 -------------- Ò»¸öHTML¸½¼þ±»ÒƳý... URL: http://python.cn/pipermail/python-chinese/attachments/20070131/13cdf0de/attachment.htm
2007年01月31日 星期三 14:56
On 1/31/07, 俊杰蔡 <yzcaijunjie at gmail.com> wrote: > > 以下是我从例程中摘录的一个方法: > > def NamedTuple(s): > """Returns a new subclass of tuple with named fields. > > >>> Point = NamedTuple('Point x y') > >>> Point.__doc__ # docstring for the new class > 'Point(x, y)' > >>> p = Point(11, y=22) # instantiate with positional args or keywords > >>> p[0] + p[1] # works just like the tuple (11, 22) > 33 > >>> p.x + p.y # fields also accessable by name > 33 > >>> p # readable __repr__ with name=value style > Point(x=11, y=22) > > """ > > f = s.split() > > typename, field_names = f[0], f[1:] > > nargs = len(field_names) > > > > def __new__(cls, *args, **kwds): > > if kwds: > > try: > > args += tuple(kwds[name] for name in field_names[len(args):]) > > except KeyError, name: > > raise TypeError('%s missing required argument: %s' % (typename, name)) > > if len(args) != nargs: > > raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, > nargs, len(args))) > > return tuple.__new__(cls, args) > > > > template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name in > field_names)) > > > > def __repr__(self, show=template.__mod__): > > return show(self) > > > > > m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup) > > m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)), > > __slots__ = (), # no per-instance dict (so instances are same size as > tuples) > > __new__ = __new__, > > __repr__ = __repr__, > > ) > > m.update((name, property(itemgetter(index))) for index, name inenumerate(field_names)) > > > > return type(typename, (tuple,), m) > > > 我对其中几个部分不懂: > > 1 在方法NamedTuple(s)中定义__new__()和__repar__()是重载么?如果是,重载不需要在类中进行么? > 2 __new__()和__repar__()各自在什么时候被调用? > 3 有很多的__slots__ ,__new__, __repr__系统变量,这些变量改怎么来了解他们的用途么? > > > 学习ing > > _______________________________________________ > python-chinese > Post: send python-chinese at lists.python.cn > Subscribe: send subscribe to python-chinese-request at lists.python.cn > Unsubscribe: send unsubscribe to python-chinese-request at lists.python.cn > Detail Info: http://python.cn/mailman/listinfo/python-chinese 注意最后一句: type(typename, (tuple,), m) 这是 metaclass 的范畴了,实际上: class Temp(tuple): a = 1 def test(self):pass 等价于: def test(self):pass Temp = type('Temp', (tuple,), {'a':1, 'test':test}) 详情请看: http://wiki.woodpecker.org.cn/moin/PythonLanguage#head-7e27906420561936f1803cf138e8504f6aa484f4 -- http://codeplayer.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://python.cn/pipermail/python-chinese/attachments/20070131/627fcff8/attachment.htm
Zeuux © 2025
京ICP备05028076号