文章目錄
- namedtuple 基本用法
- namedtuple特性
- _make(iterable)
- _asdict()
- _replace(**kwargs)
- _fields
- _fields_defaults
- 參考:
namedtuple 基本用法
Tuple還有一個兄弟,叫namedtuple。雖然都是tuple,但是功能更為強大。對于namedtuple,你不必再通過索引值進行訪問,你可以把它看做一個字典通過名字進行訪問,只不過其中的值是不能改變的。
from collections import namedtuple
Animal = namedtuple('Animal', 'name age type')
perry = Animal(name="perry", age=31, type='cat')
print(perry)
print(perry.name)
# Animal(name='perry', age=31, type='cat')
# perry
為了構造一個namedtuple需要兩個參數,分別是tuple的名字和其中域的名字。比如在上例中,tuple的名字是“Animal”,它包括三個域,分別是“name”、“age”和“type”。
Namedtuple比普通tuple具有更好的可讀性,可以使代碼更易于維護。同時與字典相比,又更加的輕量和高效。
- 但是有一點需要注意,就是namedtuple中的屬性都是不可變的。任何嘗試改變其屬性值的操作都是非法的。
- Namedtuple還有一個非常好的一點是,它與tuple是完全兼容的。也就是說,我們依然可以用索引去訪問一個namedtuple。
namedtuple特性
具名元組(namedtuple)除了擁有繼承自基本元組的所有方法之外,還提供了額外的三個方法和兩個屬性,為了防止命名沖突,這些方法都會以下劃線開頭。
_make(iterable)
這是一個類函數,參數是一個迭代器,可以使用這個函數來構建具名元組實例
Point = namedtuple('Point', ['x', 'y'])
t = [11, 22]
print(Point._make(t))
#Point(x=11, y=22)
_asdict()
實例方法,根據具名元組的名稱和其元素值,構建一個OrderedDict返回。
Point = namedtuple('Point', ['x', 'y'])
p =Point(x=11, y=22)
print(p._asdict())
#OrderedDict([('x', 11), ('y', 22)])
_replace(**kwargs)
實例方法,根據傳入的關鍵詞參數,替換具名元組的相關參數,然后返回一個新的具名元組,注意這里的拷貝方式。
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=11, y=22)
print(p._replace(x=33))
print(p)
#Point(x=33, y=22)
#Point(x=11, y=22)
_fields
這是一個實例屬性,存儲了此具名元組的元素名稱元組,在根據已經存在的具名元組創建新的具名元組的時候使用
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=11, y=22)
print(p._fields)Color = namedtuple('Color', 'red green blue')
Pixel = namedtuple('Pixel', Point._fields + Color._fields)
print(Pixel(11, 22, 128, 255, 0))# ('x', 'y')
# Pixel(x=11, y=22, red=128, green=255, blue=0)
_fields_defaults
查看具名元組類的默認值
參考:
(1)https://baijiahao.baidu.com/s?id=1613589944704758634&wfr=spider&for=pc(Python進階之路:namedtuple
)
(2). https://www.jianshu.com/p/60e6484a7088(namedtuple工廠函數精講
)