如何在yaml flux中序列化python类

2024-10-05 13:15:45 发布

您现在位置: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

你有主意了吗


Tags: importself程序yamlforobjectdefresult

热门问题