Python:确保仅使用最新协议对我的班级进行泡菜 [英] Python: Ensuring my class gets pickled only with the latest protocol

查看:59
本文介绍了Python:确保仅使用最新协议对我的班级进行泡菜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个仅可以使用协议2(以及在Python 3或更高版本)才能有意义地腌制的类.当使用较旧的协议时,会发生难以跟踪的错误.我想为该类的用户省去一些调试麻烦,所以我希望该类在使用小于2的协议进行腌制时立即引发异常.

I'm developing a class which can be meaningfully pickled only using protocol 2 (and upwards on Python 3.) When an older protocol is used, hard-to-trace bugs happen. I want to save the users of the class some debugging pain, so I want the class to immediately raise an exception if it's being pickled with a protocol of less than 2.

我该怎么办?

推荐答案

您可以实现

You can implement the __reduce_ex__() method on your class. It receives one parameter, which is the protocol version. Simply raise an exception if the version is not 2.

这篇关于Python:确保仅使用最新协议对我的班级进行泡菜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆