元祖python_python 命名元祖之实现 -- python元编程

命名元祖比起元祖写代码清晰明了很多,很想知道内部怎么实现,内部有没有增加内存,是否影响性能之类,看手册的时候,

发现有个参数可以打印出代码,惊奇的发现,其实很简单,就是用到了描述符/property而已,为什么自己就想不到呢?看样子

还没有把这些玩意真正融汇入心中;贴手册中的例子:

Point = namedtuple('Point', "x y", verbose=True)

class Point(tuple):

'Point(x, y)'

__slots__ = ()

_fields = ('x', 'y')

def __new__(_cls, x, y):

'Create new instance of Point(x, y)'

return _tuple.__new__(_cls, (x, y))

@classmethod

def _make(cls, iterable, new=tuple.__new__, len=len):

'Make a new Point 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 'Point(x=%r, y=%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 Point object replacing specified fields with new values'

result = _self._make(map(kwds.pop, ('x', 'y'), _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)

x = _property(_itemgetter(0), doc='Alias for field number 0')

y = _property(_itemgetter(1), doc='Alias for field number 1')

看到了么?其实namedtuple就是一个普通的类而已,他继承了tuple,关键的地方在于他把属性映射到了index上面,这一映射就是

通过描述符/property来完成的,原理其实很简单;关键是没意识往这方面想;

另外,非常重要的一点是,这个类完全是动态创建的,即“元编程”搞出来的东东,我想如果熟悉python的元编程,应该比较简单;

干脆自己尝试写一个吧:

def my_namedtuple(name, attrs):

if isinstance(attrs, str):

attrs = attrs.split()

import string

attrs_join = string.join(attrs, ',')

newfns = "def newfn(cls, %s): return tuple.__new__(cls, (%s))"%(attrs_join, attrs_join)

exec(newfns)

adict = {'__slots__':(), '_fields':tuple(attrs), '__doc__':'%s(%s)'%(name, attrs_join), '__new__':newfn}

import operator as op

for i,e in enumerate(attrs):

adict[e] = property(fget=op.itemgetter(i))

return type(name, (tuple,), adict)

Angle = my_namedtuple("Angle", "x y")

print dir(Angle)

angle_test = Angle(1, 15)

print angle_test

print "x,y=", angle_test.x, angle_test.y

print "0,1=", angle_test[0], angle_test[1]

Sincos = my_namedtuple("Sincos", "m n q")

sincos = Sincos(5, 9, 2)

print sincos

输出如下

['__add__', '__class__', ..., '__slots__', '__str__', '__subclasshook__', '_fields', 'count', 'index', 'x', 'y']

(1, 15)

x,y= 1 15

0,1= 1 15

(5, 9, 2)

你可能感兴趣的:(元祖python)