Python namedtuple

Python namedtuple object is part of collections module. Python namedtuple is an extension of tuple.

Python namedtuple对象是collections模块的一部分。 Python namedtuple是tuple的扩展。

Python namedtuple (Python namedtuple)

  • Python namedtuple is immutable just like tuple.

    Python namedtuple是不变的,就像tuple一样。
  • Namedtuple allows us to provide names to the elements. So we can access elements both by index value or by name.

    Namedtuple允许我们为元素提供名称。 因此,我们可以按索引值或按名称访问元素。
  • Python namedtuple helps us in writing better readable code. If the tuple has many values, using index becomes confusing. With namedtuple, we can provide descriptive names to the fields.

    Python namedtuple可帮助我们编写更好的可读性代码。 如果元组有很多值,则使用索引会造成混淆。 使用namedtuple,我们可以为字段提供描述性名称。
  • Python namedtuple field names can be any valid Python identifier. Valid identifiers consist of letters, digits, and underscores but do not start with a underscore or digit. Also, we cannot use keywords such as class, for, def, return, global, pass, or raise etc.

    Python namedtuple字段名称可以是任何有效的Python标识符。 有效标识符由字母,数字和下划线组成,但不能以下划线或数字开头。 同样,我们不能使用诸如classfor ,def,return,global, pass或raise等关键字。
  • We can specify default values to the namedtuple parameters using defaults parameter while defining the namedtuple. Note that this feature has been added in Python 3.7.

    我们可以在定义namedtuple时使用defaults参数为namedtuple参数指定默认值。 请注意,此功能已在Python 3.7中添加。
  • Python namedtuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

    Python namedtuple实例没有按实例的字典,因此它们是轻量级的,并且比常规元组不需要更多的内存。

快速访问元组 (Quick Revisit to Tuple)

Before we start with namedtuple examples, let’s have a quick look on python tuple. We will create a few tuples and print their values to console.

在开始namedtuple示例之前,让我们快速看一下python tuple。 我们将创建一些元组并将其值打印到控制台。

emp1 = ('Pankaj', 35, 'Editor')
emp2 = ('David', 40, 'Author')

for p in [emp1, emp2]:
    print(p)

for p in [emp1, emp2]:
    print(p[0], 'is a', p[1], 'years old working as', p[2])

# pythonic way
for p in [emp1, emp2]:
    print('%s is a %d years old working as %s' % p)

Output:

输出:

('Pankaj', 35, 'Editor')
('David', 40, 'Author')
Pankaj is a 35 years old working as Editor
David is a 40 years old working as Author
Pankaj is a 35 years old working as Editor
David is a 40 years old working as Author

Notice that we are using indexes to retrieve tuple elements.

注意,我们正在使用索引来检索元组元素。

Python namedtuple示例 (Python namedtuple example)

Python namedtuple is created using factory method from the collections module. This functions signature is as follows:

Python namedtuple是使用collections模块中的工厂方法创建的。 该函数签名如下:

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
  • typename: This is the name of the namedtuple object.

    typename :这是namedtuple对象的名称。
  • field_names: This is the second argument to define the field names in the namedtuple. We can define them using following formats – 'name age role', 'name,age,role', or ['name', 'age', 'role'].

    field_names :这是在namedtuple中定义字段名称的第二个参数。 我们可以使用以下格式来定义它们-'name 'name age role''name,age,role'['name', 'age', 'role']
  • rename: We can specify rename to True so that invalid fields are renamed to their index names. For example, 'name def class' will be renamed to 'name', '_1', '_2'.

    rename :我们可以将重命名指定为True,以便将无效字段重命名为其索引名称。 例如, 'name def class'将重命名为'name', '_1', '_2'
  • defaults: It’s used to define default values to the optional parameters. Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. For example, if the fieldnames are ['a', 'b', 'c'] and the defaults are (1, 2), then ‘a’ will be a required argument, ‘b’ will default to 1, and ‘c’ will default to 2.

    defaults :用于为可选参数定义默认值。 由于具有默认值的字段必须位于任何没有默认值的字段之后,因此默认值将应用于最右边的参数。 例如,如果字段名称为['a', 'b', 'c']defaults值为(1、2),则'a'将是必填参数,'b'将默认为1,而' c'将默认为2。
  • module: If module is defined, the __module__ attribute of the named tuple is set to that value. This parameter was introduced in Python 3.6 release.

    module :如果定义了__module__ ,则命名元组的__module__属性设置为该值。 此参数在Python 3.6版本中引入。

Let’s see a simple example to create namedtuple and print its values.

让我们看一个简单的示例,创建namedtuple并打印其值。

from collections import namedtuple

Employee = namedtuple('Employee', ['name', 'age', 'role'])

# below are also valid ways to namedtuple
# Employee = namedtuple('Employee', 'name age role')
# Employee = namedtuple('Employee', 'name,age,role')

emp1 = Employee('Pankaj', 35, 'Editor')
emp2 = Employee(name='David', age=40, role='Author')

for p in [emp1, emp2]:
    print(p)

# accessing via index value
for p in [emp1, emp2]:
    print('%s is a %d years old working as %s' % p)

# accessing via name of the field
for p in [emp1, emp2]:
    print(p.name, 'is a', p.age, 'years old working as', p.role)

Notice that I am using namedtuple field names to retrieve the values. More or less it’s almost the same as earlier tuple example program.

注意,我正在使用namedtuple字段名称来检索值。 它或多或少与以前的元组示例程序几乎相同。

Output:

输出:

Employee(name='Pankaj', age=35, role='Editor')
Employee(name='David', age=40, role='Author')
Pankaj is a 35 years old working as Editor
David is a 40 years old working as Author
Pankaj is a 35 years old working as Editor
David is a 40 years old working as Author

带有无效键的Python namedtuple并重命名 (Python namedtuple with invalid keys and rename)

If we use invalid keys for namedtuple names, then we will get ValueError.

如果我们对namedtuple名称使用无效的键,则将得到ValueError

try:
    Person = namedtuple('Person', 'def class')
except ValueError as error:
    print(error)

Output:

输出:

Type names and field names cannot be a keyword: 'def'

Now let’s see what happens when we specify rename as True.

现在让我们看看将重命名指定为True时会发生什么。

# rename=True will rename invalid names to index value with underscore prefix
Person = namedtuple('Person', 'name def class', rename=True)
print(Person._fields)

Output:

输出:

('name', '_1', '_2')

Notice that field names are changed to their index values prefixed with an underscore.

请注意,字段名称已更改为其索引值,并带有下划线前缀。

Python namedtuple模块 (Python namedtuple module)

# namedtuple module parameter - introduced in 3.6
Person = namedtuple('Person', 'name', module='MyPersonModule')
print(Person.__module__)

Output:

输出:

MyPersonModule

Python namedtuple其他方法 (Python namedtuple additional methods)

Let’s look at three additional methods available for namedtuple.

让我们看看可用于namedtuple的三种其他方法。

_make(可迭代) (_make(iterable))

This classmethod can be used to create namedtuple from an iterable.

此类方法可用于从可迭代对象创建namedtuple。

t = ('Lisa', 35, 'Contributor')
emp3 = Employee._make(t)
print(emp3)

Output:

输出:

Employee(name='Lisa', age=35, role='Contributor')

_asdict() (_asdict())

This is used to create an OrderedDict instance from a namedtuple.

这用于从namedtuple创建OrderedDict实例。

od = emp3._asdict()
print(od)

Output:

输出:

OrderedDict([('name', 'Lisa'), ('age', 35), ('role', 'Contributor')])

_replace(** kwargs) (_replace(**kwargs))

Python namedtuple is immutable, so we can’t change its values. This method returns a new instance of namedtuple replacing specified fields with new values.

Python namedtuple是不可变的,因此我们无法更改其值。 此方法返回namedtuple的新实例,用新值替换指定字段。

emp3 = emp3._replace(name='Lisa Tamaki', age=40)
print(emp3)

Output:

输出:

Employee(name='Lisa Tamaki', age=40, role='Contributor')

Python namedtuple附加属性 (Python namedtuple additional attributes)

There are two additional parameters in namedtuple – _fields and _fields_defaults. As the name suggests, they provide information about the fields and their default values. Python 3.7 dropped _source attribute.

namedtuple中有两个附加参数-_fields_fields_defaults 。 顾名思义,它们提供有关字段及其默认值的信息。 Python 3.7删除了_source属性

print(emp3._fields)
Gender = namedtuple('Gender', 'gender')
Person = namedtuple('Person', Employee._fields + Gender._fields)
print(Person._fields)

# _fields_defaults - introduced in Python 3.7
# Python 3.7 removed verbose parameter and _source attribute

Person1 = namedtuple('Person1', ['name', 'age'], defaults=['Pankaj', 20])
print(Person1._fields_defaults)

Output:

输出:

('name', 'age', 'role')
('name', 'age', 'role', 'gender')
{'name': 'Pankaj', 'age': 20}

Python namedtuple其他示例 (Python namedtuple miscellaneous examples)

Let’s look at some miscellaneous examples of namedtuple.

让我们看一下namedtuple的一些其他示例。

getattr() (getattr())

We can get the namedtuple field value using getattr() function too.

我们也可以使用getattr()函数获得namedtuple字段值。

emp3_name = getattr(emp3, 'name')
print(emp3_name)

Output:

输出:

Lisa Tamaki

字典命名元组 (Dict to Named Tuple)

Named tuple and Dict are very similar, so it’s no wonder that there is a quick way to convert dict to namedtuple.

命名元组和Dict非常相似,因此也难怪有一种将dict转换为namedtuple的快速方法。

d = {'age': 10, 'name': 'pankaj', 'role':'CEO'}
emp4 = Employee(**d)
print(d)
print(emp4)

Output:

输出:

{'age': 10, 'name': 'pankaj', 'role': 'CEO'}
Employee(name='pankaj', age=10, role='CEO')

摘要 (Summary)

Python namedtuple is useful in writing better code with more readability. It’s very lightweight just like tuple, so use it when you find tuples are confusing because of using numeric indexes.

Python namedtuple在编写具有更好可读性的更好代码时很有用。 就像元组一样,它非常轻巧,因此当您发现元组由于使用数字索引而造成混淆时,请使用它。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/22439/python-namedtuple

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值