序列化此对象时如何忽略成员Trivial._ignore
?
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
答案 0 :(得分:1)
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)
这样的东西会忽略任何一个(领先的)下划线
我认为这就是你想要的
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)
虽然是一种更好的方法(风格上的)
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())
这是坚持蟒蛇明确的口头禅比隐含
更好