python - 如何在 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
你有想法吗?
解决方案
在 python3 中使用:for clea,valeura in iter(sorted(self.dicta.items())):
而不是
for clea,valeura in iter(sorted(self.dicta.iteritems())):
推荐阅读
- python - 使用 Seaborn 在 Kaggle 上绘图时出错。错误说我有分类数据,即使我的数据是 int64
- python - 在 Python 中使用 Microsoft 自定义翻译器
- regex - 如何获取两个特殊字符之间的单词列表
- reactjs - 无法更新 setState
- python - 在Python中计算和提取矩形角的像素坐标
- javascript - 状态已更改,但组件不会重新加载
- django - Django模板if语句没有更新
- opencl - Opencl 3D 数组索引
- debugging - Haxe,调用新函数
- oracle - cx_Oracle.DatabaseError: ORA-01036: 非法变量名称/编号