yaml的使用

有的代码用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__

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容