namedtuple:用来构建带字段名的元组
import collections # 创建类,两种创建方法 MytupleClass = collections.namedtuple('MytupleClass', 'x y z') # MytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z']) obj = MytupleClass(11, 22, 33) # 相当于创建了一个obj对象 x=11, y=22, z=33 print(obj.x) print(obj.y) print(obj.z)
结果:
11 22 33
类._make([ ]):用列表的形式创建对象
import collections MytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z']) new = MytupleClass._make([11, 22, 44]) print(new)
结果:
MytupleClass(x=11, y=22, z=44)
x._replace():替换对象
x._asdict():转换为字典
import collections MytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z']) new = MytupleClass._make([11, 22, 44]) new = new._replace(z=9) print(new)
print(new.asdict())
结果:
MytupleClass(x=11, y=22, z=9)
OrderedDict([('x', 11), ('y', 22), ('z', 9)])