简体   繁体   English

是否可以在Python中创建与类成员持久性状态类似的行为,就像使用Java'transient'关键字那样?

[英]Is it possible to create in Python a similar behaviour to a class member persistency state, as done with Java 'transient' keyword?

I have a python data class that contains fields that I do not want to be persisted/saved/serialized (excluded as well from pickle.dump() / json.dump() /etc). 我有一个python数据类,其中包含我不想被持久化/保存/序列化的字段(也不包含在pickle.dump() / json.dump() / etc中)。

What I'm looking for can be best explained as something similar to Java transient , were I can mark a class member as transient and that member will be excluded from any persistency or serialization of that class object without any additional boilerplate code. 如果可以将类成员标记为transient并且无需任何其他样板代码的情况下,该类对象的任何持久性或序列化都将其排除,则可以将我所寻找的东西最好地解释为类似于Java transient

I've found this similar question: Can I mark variables as transient so they won't be pickled? 我发现了一个类似的问题: 我可以将变量标记为瞬态的,这样就不会被腌制吗? but it only address pickle. 但是只能解决泡菜

Is there a pythonic way of doing that? 有pythonic的方法吗?

Thanks! 谢谢!

This isn't a thing in Python simply because there is no consistent method of serialisation in the first place. 在Python中这不是一件简单的事情,因为一开始就没有一致的序列化方法。 As your linked question demonstrates, pickle uses __getstate__ , but JSON and yaml serializers don't necessarily. 如您的链接问题所示,pickle使用__getstate__ ,但JSON和yaml序列化器不一定。 You would need to override whatever code is doing the actual serialisation. 您将需要重写执行实际序列化的任何代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM