0
0

More than 1 year has passed since last update.

namedtupleについて

Last updated at Posted at 2022-12-14

namedtupleについて知ろう!

参考

namedtupleとは、pythonの標準ライブラリーcollectionsモジュールからインポートできるデータ型のこと。namedtupleは第一引数にクラス名、第二引数に属性を記述し、クラスを生成して返す関数です。

namedtupleの使い方

exam.py
from collections import namedtuple

Human = namedtuple('Human', ['name', 'gender'])

my_info = Human('taro', 'man')

print('名前:', my_info.name)
print('性別:', my_info.gender)
print('インデックス0:', my_info[0])
print('インデックス1:', my_info[1])
# 可変長引数
print('可変長引数:', *my_info)
# アンパック
name, gender = my_info
print('アンパック:', name, gender)

>>>
名前: taro
性別: man
インデックス0: taro
インデックス1: man
可変長引数: taro man
アンパック: taro man

namedtupleでは、ファクトリ関数(クロージャ)が文字列に対してsplite関数を呼び出す。そのため、上記コードのリスト部分のような2つの要素でも、以下のコードのように文字列として渡すこともできる。

exam2.py
from collections import namedtuple

gender = namedtuple('man', 'jiro taro')

namedtupleの継承

namedtupleはクラスを生成するクラスなので、継承を行いメソッドやプロパティを追加することができる。

exam3.py
from collections import namedtuple

Human = namedtuple('Human', ['name', 'gender'])


class Human_kind(Human):
    def name_categorize(self):
        if len(self.name) >= 6:
            return 'longname'
        else:
            return 'shortname'


H = Human_kind('sorajiro', 'man')
print(H.name_categorize())

メソッドを使ってみよう!

既存のリストからnamedtupleを作る_makeメソッド

exam4.py
from collections import namedtuple

Human = namedtuple('Human', ['name', 'age'])

data = ['saku', 22]
human_data = Human._make(data)
print(human_data)
print(human_data.name)
print(human_data.age)

>>>
Human(name='saku', age=22)
saku
22

フィールド名を取得する_fieldsメソッド

exam5.py
from collections import namedtuple

Human = namedtuple('Human', ['name', 'age'])

H = Human('saku', 22)
print(H._fields)

>>>('name', 'age')

辞書型で情報を取得する_asdict

exam6.py
from collections import namedtuple

Human = namedtuple('Human', ['name', 'age'])

H = Human('jiro', 78)
H_dict = H._asdict()

print(type(H_dict))
print(H_dict)
print(H_dict['name'])
print(H_dict['age'])

>>>
<class 'dict'>
{'name': 'jiro', 'age': 78}
jiro
78
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0