PyYAML - how to deal with composition

走远了吗. 提交于 2020-01-07 03:37:09

问题


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)

How would be the best way to do something like this in YAML?

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/42227826/pyyaml-how-to-deal-with-composition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!