本文介绍了使用 PyYAML 序列化对象时如何忽略成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在序列化这个对象时忽略成员Trivial._ignore?

How can ignore the member Trivial._ignore when serializing this object?

import yaml
class Trivial(yaml.YAMLObject):
    yaml_tag = u'!Trivial'
    def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3

t = Trivial()
print(yaml.dump(t))

印刷品

!Trivial
_ignore: 3
a: 1
b: 2

推荐答案

def my_yaml_dump(yaml_obj):
    my_ob = deepcopy(yaml_obj)
    for item in dir(my_ob):
        if item.startswith("_") and not item.startswith("__"):
             del my_ob.__dict__[item]
    return yaml.dump(my_ob)

这样的事情会忽略带有单个(前导)下划线的任何内容

something like this would ignore anything with a single (leading) underscore

我想这就是你想要的

class Trivial(yaml.YAMLObject):
    yaml_tag = u'!Trivial'
    def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3
    @classmethod
    def to_yaml(cls, dumper, data):
        # ...
        my_ob = deepcopy(data)
        for item in dir(my_ob):
            if item.startswith("_") and not item.startswith("__"):
                del my_ob.__dict__[item]
        return dumper.represent_yaml_object(cls.yaml_tag, my_ob, cls,
                                                flow_style=cls.yaml_flow_style)

虽然是更好的方法(风格上)

although a better method (stylistically)

class SecretYamlObject(yaml.YAMLObject):
     hidden_fields = []
     @classmethod
     def to_yaml(cls,dumper,data):
         new_data = deepcopy(data)
         for item in cls.hidden_fields:
             del new_data.__dict__[item]
         return dumper.represent_yaml_object(cls.yaml_tag, new_data, cls,
                                            flow_style=cls.yaml_flow_style)

class Trivial(SecretYamlObject):
     hidden_fields = ["_ignore"]
     yaml_tag = u'!Trivial'
     def __init__(self):
        self.a = 1
        self.b = 2
        self._ignore = 3

print yaml.dump(Trivial())

这是秉承python的口头禅,显式优于隐式

this is adhering to pythons mantra of explicit is better than implicit

这篇关于使用 PyYAML 序列化对象时如何忽略成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 01:52