补充pylover's answer:如果在某个时候需要对序列化/反序列化过程进行更多控制,请尝试yamlable。我们把这个包作为一个包来绑定,这样就可以获得更多的控制权。在
在您的例子中: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)
如果需要更改默认行为,例如只转储某些字段,或更改其结构以进行转储,或在加载时执行某些自定义实例创建,请取消对相应方法的注释。在