yaml的使用

2022-06-19  本文已影响0人  菌子甚毒

有的代码用yaml保存config参数。

  1. 下载yaml
    pip install pyyaml
  2. 加载yaml文件
config_name = 'config_name'
config = yaml.safe_load(open(f'/pathtoyamlfile/{config_name}.yaml', 'r'))
  1. 加载的变量是dic,写一个类将字典转化为类,这样就能通过config.param调用。
class Dict2Class(object):
    def __init__(self, my_dict):  
        for key in my_dict:
            setattr(self, key, my_dict[key])

https://www.runoob.com/python/python-func-setattr.html
setattr(object, name, value)

"""
以下展示了两种setattr的方式,
  1. 一种是直接在init中使用,set的对象是self。
  2. 一种是创建了实体之后使用,set的对象是实体。
"""
class Testclass(object):
    def __init__(self,):
        self.bar = 1
        setattr(self,'bar',2)
        setattr(self,'bar2',3)

>>> t = Testclass()
>>> t.bar   # 2
>>> t.bar2  # 3
>>> setattr(t,'bar3',4)
>>> t.bar3  # 4

转换字典直接t.__dict__

上一篇 下一篇

猜你喜欢

热点阅读