在 Python 等动态语言中,我知道可以轻松地将 YAML 映射转换为对象。它可以是一个非常强大的功能并且可以节省大量的编码。
当我尝试将.yaml
文件映射到对象时遇到问题。
文件: objtest.yaml
---
test: yaml test
option: this is option
...
我的代码:
class MyTest(object):
pass
testObj = MyTest()
f = open(os.path.join(os.path.dirname(__file__), 'objtest.yaml'))
rawData = yaml.safe_load(f)
print rawData
testObj.__dict__ = yaml.load(f)
f.close()
print testObj
STDOUT(带回溯):
{'test': 'yaml test', 'option': 'this is option'}
Traceback (most recent call last):
File "C:/CROW/ATE/Workspace/Sandbox/test.py", line 23, in <module>
testObj.__dict__ = yaml.load(f)
TypeError: __dict__ must be set to a dictionary, not a 'NoneType'
问题:
如您所见,文件已加载到但当我尝试将文件加载到rawData
类实例时出现问题。testObj
.yaml
任何想法我做错了什么?