PS:非原创,网友的代码
代码:
def namedtuple(tuple_name, attrs):
class Meta(type):
def __call__(self, *args):
return type.__call__(self, args)
attrs_set = set(attrs)
def __init__(self, args):
for key, value in zip(attrs, args):
self.__dict__[key]=value
def __str__(self):
values = [str(x) for x in self.__dict__.values()]
return tuple_name+'(' + ', '.join(values) + ')'
def to_dict(self):
return self.__dict__
return Meta(tuple_name, (tuple,),{'attr_keys':attrs_set,'__init__':__init__,'__str__':__str__,'to_dict':to_dict})
说明:
最关键的是
def __call__(self, *args):
return type.__call__(self, args)
通过拦截类的实例化过程,将参数list传入元祖,args再传入下面的__init__
中,确保只有一个参数。
def __init__(self, args):
for key, value in zip(attrs, args):
self.__dict__[key]=value
在__init__
中,通过迭代将参数传入self.__dict__
字典中,之后即可用p.x的方式调用属性。
使用:
In [1]: from namedtuple_like import namedtuple
In [2]: Point = namedtuple('p',['x','y'])
In [3]: p = Point(1,2)
In [4]: p.x
Out[4]: 1
In [5]: p.y
Out[5]: 2
In [8]: p.to_dict()
Out[8]: {'x': 1, 'y': 2}
In [12]: print(p)
p(1, 2)