【发布时间】:2011-01-27 10:16:06
【问题描述】:
我有以下 Python 2.6 程序和 YAML 定义(使用 PyYAML):
import yaml
x = yaml.load(
"""
product:
name : 'Product X'
sku : 123
features :
- size : '10x30cm'
weight : '10kg'
"""
)
print type(x)
print x
这导致以下输出:<type 'dict'>
{'product': {'sku': 123, 'name': 'Product X', 'features': [{'weight': '10kg', 'size': '10x30cm'}]}}
可以用x的字段创建对象吗?
我想要以下:
print x.features[0].size
我知道可以从现有类创建和实例化,但这不是我想要的特定场景。
编辑:
- 更新了关于“强类型对象”的令人困惑的部分。
- 按照 Alex Martelli 的建议,将对
features的访问权限更改为索引器
【问题讨论】: