我对 Python 非常陌生,并试图弄清楚如何创建一个具有可通过属性名称或索引访问的值的对象。例如,os.stat() 返回 stat_result 或 pwd.getpwnam() 返回 struct_passwd 的方式。
在试图弄清楚这一点时,我只遇到过上述类型的 C 实现。 Python 中没有什么特别的内容。创建此类对象的 Python 本机方法是什么?
如果这已经被广泛报道,我深表歉意。在寻找答案的过程中,我一定错过了一些使我无法找到答案的基本概念。
Python 2.6 推出集合.namedtuple http://docs.python.org/library/collections.html#collections.namedtuple让这变得容易。对于较旧的 Python 版本,您可以使用命名元组配方 http://code.activestate.com/recipes/500261/.
直接引用文档:
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)