gpt4 book ai didi

python - 为什么 python `__setstate__` 接受 `None` 作为参数?

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:04 24 4
gpt4 key购买 nike

我正在浏览 serge pygame engine 中的一些代码我在 serge.serialize 中遇到了一些我无法理解的东西:

def __setstate__(self, state=None):
"""Initialize the object to the given state for unpickling"""
self.initial_properties = Bag()
#
# Initialize first from the defaults and then from the live state
for this_state in (self.__class__._getProperties(), state):
if this_state:
for name, value in this_state:
setattr(self, name, value)
setattr(self.initial_properties, name, value)

此方法是从 Serializable 对象中检索到的。我感到困惑的是为什么 __setstate__ 中的 state 参数的默认值为 None。为什么在 unpickling 对象时不将状态发送到 __setstate__,这在什么情况下有用?

最佳答案

如果您的类完全依赖于 __getstate__/__setstate__ 进行 pickling,这将无用。

作为 __setstate__ 上的文档解释:

Upon unpickling, if the class defines __setstate__(), it is called with the unpicked state… If __getstate__() returns a false value, the __setstate__() method will not be called upon unpicking.

所以,如果你的__getstate__返回None,它不会在__setstate__时传回给你;你只是不会接到电话。

但是,请注意在 2.x version ,这对于经典类(class)而言并非如此。对于经典类,“如果一个类同时定义了 __getstate__()__setstate__(),则状态对象不必是字典,这些方法可以做它们想做的事” (事实上​​ ,我相信在某些情况下,任何虚假值都会变成 {},这并没有很好地记录,但相同的 if 语句可以处理......)

不过,这并不能解释为什么您需要默认值……如果您可以获得 None,当然,您需要编写处理 None 的代码……但是您不需要编写根本不获取参数的代码,对吧?

但是,您可能会这样做是有原因的。

首先,请注意这个特定类的 __setstate__ 比平常做的更多:它“首先从默认状态,然后从实时状态”初始化。因此,从默认值进行初始化的单元测试非常有用。

最重要的是,如果您定义自定义 __reduce__方法和 unreducer,没有理由它必须遵循与默认 unreducer 完全相同的规则。或者当然没有理由它必须调用 __setstate__ 根本——但是如果你,比如说,构建一个你希望用户子类化的基类,使你的 unreducer尽可能按照默认方式工作,因此您的用户可以覆盖 __setstate__ 而不是添加他们自己的整个 __reduce__ 实现。

同样,如果您在 pickle/copyreg 之上构建您自己的序列化程序,而不是按原样使用它,您的代码不必使用与 pickle 完全相同的规则。同样,它没有理由必须使用甚至相似 规则,但这样做可能会使您的用户更容易扩展您的类。

这些是否适用于 serge,我不知道,但它们都可以轻松应用于您可能想要构建的各种类型。

关于python - 为什么 python `__setstate__` 接受 `None` 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21841828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com