基本定义
collections.
namedtuple
(typename, field_names, *, rename=False, defaults=None, module=None)
(1)返回一个名为typename的新元组子类
(2)新的子类用于创建类似元组的对象,这些对象具有可通过属性查找访问的字段以及可索引和可迭代的字段field_names
typename
(1)typename表示这个子类的名字,比如C++、python、Java中的类名
field_names
(1)field_names是一个字符串序列,例如['x','y']
(2)field_names可以是单个字符串,每个字段名都用空格或逗号分隔,例如'x y'或'x,y'
others
(1)其它的参数并不常用,这里不再介绍啦
基本样例
from collections import namedtuple
# 基本例子
Point = namedtuple('Point',['x','y']) # 类名为Point,属性有'x'和'y'
p = Point(11, y=22) # 用位置或关键字参数实例化,因为'x'在'y'前,所以x=11,和函数参数赋值一样的
print(p[0]+p[1]) # 我们也可以使用下标来访问
# 33
x, y = p # 也可以像一个元组那样解析
print(x,y)
# (11, 22)
print(p.x+p.y) # 也可以通过属性名来访问
# 33
print(p) # 通过内置的__repr__函数,显示该对象的信息
# Point(x=11, y=22)
classmethod somenamedtuple.
_make
(iterable)
(1)从一个序列或者可迭代对象中直接对field_names中的属性直接赋值,返回一个对象
t = [11, 22] # 列表 list
p = Point._make(t) # 从列表中直接赋值,返回对象
print(Point(x=11, y=22))
# Point(x=11, y=22)
classmethod somenamedtuple._asdict
()
(1)之前也说过了,说它是元组,感觉更像一个带名字的字典
(2)我们也可以直接使用_asdict()将它解析为一个字典dict
p = Point(x=11, y=22) # 新建一个对象
d = p._asdict() # 解析并返回一个字典对象
print(d)
# {'x': 11, 'y': 22}
classmethod somenamedtuple._replace
(**kwargs)
(1)这是对某些属性的值,进行修改的,从replace这个单词就可以看出来
(2)注意该函数返回的是一个新的对象,而不是对原始对象进行修改
p = Point(x=11, y=22) # x=11,y=22
print(p)
# Point(x=11, y=22)
d = p._replace(x=33) # x=33,y=22 新的对象
print(p)
# Point(x=11, y=22)
print(d)
# Point(x=33, y=22)
classmethod somenamedtuple._fields
(1)该方法返回该对象的所有属性名,以元组的形式
(2)因为是元组,因此支持加法操作
print(p._fields) # 查看属性名
# ('x', 'y')
Color = namedtuple('Color', 'red green blue')
Pixel = namedtuple('Pixel', Point._fields + Color._fields) # 新建一个子类,使用多个属性名
q = Pixel(11, 22, 128, 255, 0)
print(q)
# Pixel(x=11, y=22, red=128, green=255, blue=0)
classmethod somenamedtuple._field_defaults
(1)该方法是python3.8新增的函数,因为我的版本是3.6,无法验证其正确性
(2)下面给出官方的示例
Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
print(Account._field_defaults)
#{'balance': 0}
print(Account('premium'))
#Account(type='premium', balance=0)
getattr()函数
(1)用来获得属性的值
print(getattr(p, 'x'))
# 11
字典创建namedtuple()
(1)从字典来构建namedtuple的对象
d = {'x': 11, 'y': 22} # 字典
p = Point(**d) # 双星号是重点
print(p)
# Point(x=11, y=22)
CSV OR Sqlite3
(1)同样可以将从csv文件或者数据库中读取的文件存储到namedtuple中
(2)这里每次存的都是一行的内容
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "r"))):
# 这里每行返回一个对象 注意!
print(emp.name, emp.title)
import sqlite3
conn = sqlite3.connect('/companydata') # 连接数据库
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
# 每行返回一个对象 注意!
print(emp.name, emp.title)
类的继承
(1)接下来用deepmind的开源项目graph_nets中的一段代码来介绍
NODES = "nodes"
EDGES = "edges"
RECEIVERS = "receivers"
SENDERS = "senders"
GLOBALS = "globals"
N_NODE = "n_node"
N_EDGE = "n_edge"
GRAPH_DATA_FIELDS = (NODES, EDGES, RECEIVERS, SENDERS, GLOBALS)
GRAPH_NUMBER_FIELDS = (N_NODE, N_EDGE)
class GraphsTuple(
# 定义元组子类名 以及字典形式的键名(属性名)
collections.namedtuple("GraphsTuple",
GRAPH_DATA_FIELDS + GRAPH_NUMBER_FIELDS)):
# 这个函数用来判断依赖是否满足,和我们的namedtuple关系不大
def _validate_none_fields(self):
"""Asserts that the set of `None` fields in the instance is valid."""
if self.n_node is None:
raise ValueError("Field `n_node` cannot be None")
if self.n_edge is None:
raise ValueError("Field `n_edge` cannot be None")
if self.receivers is None and self.senders is not None:
raise ValueError(
"Field `senders` must be None as field `receivers` is None")
if self.senders is None and self.receivers is not None:
raise ValueError(
"Field `receivers` must be None as field `senders` is None")
if self.receivers is None and self.edges is not None:
raise ValueError(
"Field `edges` must be None as field `receivers` and `senders` are "
"None")
# 用来初始化一些参数 不是重点
def __init__(self, *args, **kwargs):
del args, kwargs
# The fields of a `namedtuple` are filled in the `__new__` method.
# `__init__` does not accept parameters.
super(GraphsTuple, self).__init__()
self._validate_none_fields()
# 这就用到了_replace()函数,注意只要修改了属性值
# 那么就返回一个新的对象
def replace(self, **kwargs):
output = self._replace(**kwargs) # 返回一个新的实例
output._validate_none_fields() # pylint: disable=protected-access 验证返回的新实例是否满足要求
return output
# 这是为了针对tensorflow1版本的函数
# 返回一个拥有相同属性的对象,但是它的属性值是输入的大小和类型
def map(self, field_fn, fields=GRAPH_FEATURE_FIELDS): # 对每个键应用函数
"""Applies `field_fn` to the fields `fields` of the instance.
`field_fn` is applied exactly once per field in `fields`. The result must
satisfy the `GraphsTuple` requirement w.r.t. `None` fields, i.e. the
`SENDERS` cannot be `None` if the `EDGES` or `RECEIVERS` are not `None`,
etc.
Args:
field_fn: A callable that take a single argument.
fields: (iterable of `str`). An iterable of the fields to apply
`field_fn` to.
Returns:
A copy of the instance, with the fields in `fields` replaced by the result
of applying `field_fn` to them.
"""
return self.replace(**{k: field_fn(getattr(self, k)) for k in fields}) # getattr(self, k) 获取的是键值对中的值, k表示键