问题描述
我一直在尝试使用YAML,因为我喜欢它的可读性。
I've been trying to use YAML as I love the readability of it.
但是,我对最佳的组件放置方式有些困惑
However, I'm a bit stumped at the best way to put in components/deal with composition.
让我说这是我要复制的课程:
Let's say I have this as a class I'm trying to replicate:
basicai = aggressiveAI()
fightercomponent = fighter(strength=10, dexterity=5, death=dramaticdeath())
orc = Object(name='orc', hp=100, fighter=fightercomponent, ai=basicai)
如何
大多数情况下,我希望最终无法获得一长串专门命名的组件对象
Mostly, I'd like to be able to not end up with a long list of specifically named component objects and main objects all spread out.
推荐答案
假设您有适当的构造函数和表示符来创建对象,则可以执行以下操作: / p>
Assuming that you have proper constructors and representers to create the objects, you can do:
- !AggresiveAI &basicai
- !Fighter &fightercomponent
strength: 10
dexterity: 5
death: dramaticdeath
- !Object
name: orc
hp: 100
fighter: *fightercomponent
ai: *basicai
唯一有问题的是,由于YAML存储对象而不是函数调用,因此您对 dramaticdeath
的函数调用。因此,请在类 Fighter
The only thing problematic is your function call to dramaticdeath
as YAML stores objects and not function calls. So make that a lookup from the string to the function in the __init__
method of class Fighter
顶层不必是列表,例如将顶层映射。只要在使用别名之前先确定已定义锚即可。
The toplevel doesn't have to be a list, you can e.g. make the toplevel a mapping. Just make sure your anchors are defined before using them in aliases.
这篇关于PyYAML-如何处理合成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!