1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】Enumを使わない静的データ管理

1
Posted at

背景

簡易なプログラムを書く際、わざわざデータベースを立てたり設定ファイルから定数を取得するのも面倒な時は、データをプログラムにハードコーディングしてしまう場合もしばしばあります。

Enumを使うとスマートに書きやすいと前回 【Python】Enumで静的データ管理 書きました。

しかし、Enumはメンバーの命名が必要なため、命名コストが重たいときは向いてません。そこで命名をしないで済む方法を調べ、実装してみました。

結論としては、namedtupleをclass内listに格納して管理します。
listの要素に辞書型を使ってもいいですが、変数へのアクセスがnamedtupleの方が書きやすいのでnamedtupleを使用します。

ちなみに、わざわざclass内にlistを設けるのは、変数のスコープを狭めたいからです。

環境

Python3.6.8

3.7以上からはdataclassesなるものがあるので、使えるならそちらの方がスマートに書けるかもしれません(全然触ってないため分かりませんが)。

.py
from collections import namedtuple

class MonsterData:

    Monster = namedtuple('Monster', ['id', 'en', 'ja'])

    members = [
        Monster(0, 'None', '無し'),
        Monster(1, 'Slime', 'スライム'),
        Monster(2, 'Killer Ant', 'キラーアント'),
        Monster(3, 'Goblin', 'ゴブリン'),
        Monster(4, 'Lizardman', 'リザードマン'),
        Monster(5, 'Ogre', 'オーガ'),
        Monster(6, 'Dragon', 'ドラゴン'),
    ]

    @classmethod
    def get_by_id(cls, id):
        for c in cls.members:
            if id == c.id:
                return c
        # default
        return cls.members[0]

    @classmethod
    def get_by_ja(cls, ja):
        for c in cls.members:
            if ja == c.ja:
                return c
        # default
        return cls.members[0]



if __name__ == "__main__":

    print(MonsterData.get_by_id(1).ja)
    print(MonsterData.get_by_id(1).en)
    print('=====')
    print(MonsterData.get_by_ja('ゴブリン').id)
    print(MonsterData.get_by_ja('ゴブリン').en)

スライム
Slime
=====
3
Goblin

変数の命名コストを省けました。

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?