LoginSignup
0
0

More than 1 year has passed since last update.

クラスインスタンスに読み込んだ設定を反映するメモ

Posted at

きっかけ

  • PyYAMLで読み込んだ設定をクラスインスタンスに反映させる処理を汎化したかった

YAMLファイル(test.yaml)の記述

name: 'Iceberg'
type: 'double-handed sword'
element: 'ice'
range: 1

ソースコード

  • 下記の実行ファイルと前述のYAMLファイルは同じディレクトリにある前提
import yaml

class TestClass():
    def __init__(self):
        self.name = ''
        self.type = ''
        self.element = ''

    def load_config(self, config_path):
        with open(config_path, encoding='utf-8') as file:
            loaded_data = yaml.safe_load(file)
        
        for class_loop in vars(self):
            if class_loop in loaded_data.keys():
                setattr(self, class_loop, loaded_data[class_loop])

tc = TestClass()
tc.load_config('test.yaml')

print(vars(tc))

結果

{'name': 'Iceberg', 'type': 'double-handed sword', 'element': 'ice'}

参考

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