Python_collections_namedtuple可命名元組

namedtuple:用來構建帶字段名的元組spa

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)

結果:code

11
22
33

類._make([ ]):用列表的形式建立對象對象

import collections
MytupleClass = collections.namedtuple('MytupleClass',[ 'x', 'y', 'z'])
new = MytupleClass._make([11, 22, 44])
print(new)

結果:blog

MytupleClass(x=11, y=22, z=44)

x._replace():替換對象io

x._asdict():轉換爲字典class

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())

結果:import

MytupleClass(x=11, y=22, z=9)OrderedDict([('x', 11), ('y', 22), ('z', 9)])
相關文章
相關標籤/搜索