首页 > 解决方案 > 如何在 yaml Flux 中序列化一个 python 类

问题描述

我有这个 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

你有想法吗?

标签: pythonyamlpyyaml

解决方案


在 python3 中使用:for clea,valeura in iter(sorted(self.dicta.items())):而不是

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

推荐阅读