typing.NamedTuple - 改进的命名元组
Python 3.6 中添加的类型化模块的NamedTuple类是集合模块中的 namedtuple 类的年轻兄弟。主要区别在于更新了用于定义新记录类型的语法并增加了对类型提示的支持。与字典一样, NamedTuples 包含散列到特定值的键。但相反,它同时支持键值访问和迭代访问,这是字典所缺乏的功能。
创建 NamedTuple
NamedTuple 可以使用以下语法创建:
class class_name(NamedTuple):
field1: datatype
field2: datatype
这相当于:
class_name = collections.namedtuple('class_name', ['field1', 'field2'])
例子:
Python3
# importing the module
from typing import NamedTuple
# creating a class
class Website(NamedTuple):
name: str
url: str
rating: int
# creating a NamedTuple
website1 = Website('GeeksforGeeks',
'geeksforgeeks.org',
5)
# displaying the NamedTuple
print(website1)
Python3
# importing the module
from typing import NamedTuple
# creating a class
class Website(NamedTuple):
name: str
url: str
rating: int
# creating a NamedTuple
website1 = Website('GeeksforGeeks',
'geeksforgeeks.org',
5)
# accessing using index
print("The name of the website is : ", end = "")
print(website1[0])
# accessing using name
print("The URL of the website is : ", end = "")
print(website1.url)
# accessing using getattr()
print("The rating of the website is : ", end = "")
print(getattr(website1, 'rating'))
Python3
# importing the module
from typing import NamedTuple
# creating a class
class Website(NamedTuple):
name: str
url: str
rating: int
# creating a NamedTuple
website1 = Website('GeeksforGeeks',
'geeksforgeeks.org',
5)
# changing the attribute value
website1.name = "Google"
输出:
Website(name='GeeksforGeeks', url='geeksforgeeks.org', rating=5)
访问操作
- 按索引访问: namedtuple() 的属性值是有序的,可以使用索引号访问,不像字典不能按索引访问。
- 通过键名访问:在字典中也允许通过键名访问。
- 使用 getattr():这是通过将 namedtuple 和 key-value 作为参数来访问值的另一种方法。
例子:
Python3
# importing the module
from typing import NamedTuple
# creating a class
class Website(NamedTuple):
name: str
url: str
rating: int
# creating a NamedTuple
website1 = Website('GeeksforGeeks',
'geeksforgeeks.org',
5)
# accessing using index
print("The name of the website is : ", end = "")
print(website1[0])
# accessing using name
print("The URL of the website is : ", end = "")
print(website1.url)
# accessing using getattr()
print("The rating of the website is : ", end = "")
print(getattr(website1, 'rating'))
输出:
The name of the website is : GeeksforGeeks
The URL of the website is : geeksforgeeks.org
The rating of the website is : 5
字段是不可变的。因此,如果我们尝试更改值,则会收到属性错误:
Python3
# importing the module
from typing import NamedTuple
# creating a class
class Website(NamedTuple):
name: str
url: str
rating: int
# creating a NamedTuple
website1 = Website('GeeksforGeeks',
'geeksforgeeks.org',
5)
# changing the attribute value
website1.name = "Google"
输出:
AttributeError: can't set attribute