如何在Yaml Flux中序列化python类

时间:2018-08-02 13:02:04

标签: python yaml pyyaml

我有这个python程序:

import yaml
import pprint

class DictProductCart(object):

    def __init__(self, dicta, dictb):
        self.dicta = dicta
        self.dictb = dictb

    def __repr__(self):
        result = str()
        chaine=str()
        for clea,valeura in iter(sorted(self.dicta.iteritems())):
            chaine = "%s: %s,\n" % (clea,self.dictb)
            result = result + chaine
        return result

yaml_str= """\
!!python/object:__main__.DictProductCart
dicta: {a: 1, b: 2}
dictb: {i: 10, j: 20}
"""
testdata = yaml.load(yaml_str)
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(testdata) 

结果正常:

a: {'i': 10, 'j': 20},
b: {'i': 10, 'j': 20},

现在,我将yaml数据存储在一个文件中:

!!python/object:__main__.DictProductCart
dicta: {a: 1, b: 2}
dictb: {i: 10, j: 20}

但是当我运行程序时,出现此错误:

yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object:mod_dictproductcart.DictProductCart'
  in "toto.yaml", line 1, column 1

你有个主意吗?

1 个答案:

答案 0 :(得分:0)

在python3中使用:for clea,valeura in iter(sorted(self.dicta.items())):代替

for clea,valeura in iter(sorted(self.dicta.iteritems())):