【发布时间】:2013-11-05 13:44:56
【问题描述】:
在 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,但当我尝试将 .yaml 文件加载到类实例 testObj 时出现问题。
任何想法我做错了什么?
【问题讨论】: