为了补充pylover 的回答:如果在某些时候您需要对序列化/反序列化过程进行更多控制,请尝试yamlable。我为我们的一些生产代码编写了这个包,以便对 yaml 到对象的绑定有更多的控制。
在您的示例中:
import yaml
import sys
from yamlable import YamlAble, yaml_info
@yaml_info(yaml_tag_ns='myyaml')
class StateMachine(YamlAble):
def __init__(self, states, connections):
self.states = states
self.connections = connections
# def to_yaml_dict(self):
# return vars(self)
#
# @classmethod
# def from_yaml_dict(cls, dct, yaml_tag):
# return StateMachine(**dct)
@yaml_info(yaml_tag_ns='myyaml')
class State(YamlAble):
def __init__(self, name):
self.name = name
# def to_yaml_dict(self):
# return vars(self)
#
# @classmethod
# def from_yaml_dict(cls, dct, yaml_tag):
# return State(**dct)
@yaml_info(yaml_tag_ns='myyaml')
class Connection(YamlAble):
def __init__(self, pim):
self.pim = pim
# def to_yaml_dict(self):
# return vars(self)
#
# @classmethod
# def from_yaml_dict(cls, dct, yaml_tag):
# return Connection(**dct)
if __name__ == '__main__':
o = yaml.safe_load("""
!yamlable/myyaml.StateMachine {
states: [
!yamlable/myyaml.State { name: p1 },
!yamlable/myyaml.State { name: p2 },
!yamlable/myyaml.State { name: p3 },],
connections:
[ !yamlable/myyaml.Connection { 'pim' : [p1,p2]}]}
""")
print(o.states[0].name)
print(o.states[1].name)
print(o.connections[0].pim)
print(yaml.safe_dump(o))
# Note: these also work
# print(o.loads_yaml(""" ... """))
# print(o.dumps_yaml())
sys.exit(0)
如果您需要更改默认行为,例如仅转储某些字段,或更改其结构以进行转储,或在加载时执行一些自定义实例创建,请取消注释相应的方法。
有关更多详细信息,请参阅yamlable 文档