可通过属性名称或索引选项访问的结构

Bru*_*oia 7 python namedtuple data-structures

我是Python的新手,并试图弄清楚如何创建一个具有可通过属性名称或索引访问的值的对象.例如,os.stat()返回stat_result或pwd.getpwnam()的方式返回struct_passwd.

在试图找出它时,我只遇到了上述类型的C实现.Python中没有特别的东西.创建这种对象的Python本机方法是什么?

如果已经广泛报道,我道歉.在寻找答案时,我必须遗漏一些基本概念,这使我无法找到答案.

And*_*lke 5

Python 2.6引入了collections.namedtuple来简化这一过程.使用较旧的Python版本,您可以使用命名的元组配方.

直接从文档引用:

>>> 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)
Run Code Online (Sandbox Code Playgroud)


λ J*_*kas 3

您不能使用与 os.stat() 和其他结果对象相同的实现。然而,Python 2.6 有一个新的工厂函数,可以创建一个类似的数据类型,称为命名元组。命名元组是其槽也可以通过名称来寻址的元组。根据文档,命名元组不需要比常规元组更多的内存,因为它们没有每个实例的字典。工厂函数签名是:

collections.namedtuple(typename, field_names[, verbose])  
Run Code Online (Sandbox Code Playgroud)

第一个参数指定新类型的名称,第二个参数是包含字段名称的字符串(空格或逗号分隔),最后,如果 verbose 为 true,工厂函数还将打印生成的类。

例子

假设您有一个包含用户名和密码的元组。要访问用户名,您可以在位置 0 处获取该项目,并在位置 1 处访问密码:

credential = ('joeuser', 'secret123')  
print 'Username:', credential[0]  
print 'Password:', credential[1]  
Run Code Online (Sandbox Code Playgroud)

这段代码没有任何问题,但元组不是自记录的。您必须查找并阅读有关元组中字段定位的文档。这就是命名元组可以发挥作用的地方。我们可以将前面的示例重新编码如下:

import collections  
# Create a new sub-tuple named Credential  
Credential = collections.namedtuple('Credential', 'username, password')  

credential = Credential(username='joeuser', password='secret123')  

print 'Username:', credential.username  
print 'Password:', credential.password  
Run Code Online (Sandbox Code Playgroud)

如果您对新创建的凭据类型的代码感兴趣,可以在创建类型时将 verbose=True 添加到参数列表中,在这种特殊情况下,我们会得到以下输出:

import collections  
Credential = collections.namedtuple('Credential', 'username, password', verbose=True)  

class Credential(tuple):                                       
    'Credential(username, password)'                       

    __slots__ = ()   

    _fields = ('username', 'password')   

    def __new__(_cls, username, password):  
        return _tuple.__new__(_cls, (username, password))   

    @classmethod  
    def _make(cls, iterable, new=tuple.__new__, len=len):  
        'Make a new Credential 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 'Credential(username=%r, password=%r)' % self  

    def _asdict(t):  
        'Return a new dict which maps field names to their values'  
        return {'username': t[0], 'password': t[1]}  

    def _replace(_self, **kwds):  
        'Return a new Credential object replacing specified fields with new values'  
        result = _self._make(map(kwds.pop, ('username', 'password'), _self))  
        if kwds:  
            raise ValueError('Got unexpected field names: %r' % kwds.keys())  
        return result  

    def __getnewargs__(self):  
        return tuple(self)  

    username = _property(_itemgetter(0))  
    password = _property(_itemgetter(1))  
Run Code Online (Sandbox Code Playgroud)

命名元组不仅提供按名称访问字段的功能,还包含辅助函数,例如 _make() 函数,该函数有助于从序列或可迭代对象创建 Credential 实例。例如:

cred_tuple = ('joeuser', 'secret123')  
credential = Credential._make(cred_tuple) 
Run Code Online (Sandbox Code Playgroud)

nametuple 的 python 库文档有更多信息和代码示例,所以我建议你看一下。