【问题标题】:Python class setup for serialization without pickle没有pickle的用于序列化的Python类设置
【发布时间】:2013-01-16 13:28:53
【问题描述】:

场景

我正在寻找一种在 python 中面向对象的方法,它可以将类的实例保存在数据文件中,并在稍后的时间点再次加载它。我目前的做法是这样的:

class A(object):
    def __init__(self, ComplexParam1, ComplexParam2):
        self.ComplexParam1 = ComplexParam1
        self.ComplexParam2 = ComplexParam2

    @staticmethod
    def Create(EasyParam1, EasyParam2):
        #do some complex calculation to get ComplexParam1 and ComplexParam2 from EasyParam1 and EasyParam2
        return A(ComplexParam1, ComplexParam2)        

    def Save(self, Filename):
        #write ComplexParam1 and ComplexParam2 to disc

    @staticmethod
    def Load(Filename):
        #read ComplexParam1 and ComplexParam2 and call constructor
        return A(ComplexParam1, ComplexParam2)

如您所见,ComplexParam1ComplexParam2 是计算参数,不用于对象 A 的首次创建,因为它们获取起来非常复杂,而 EasyParam1EasyParam2 是“已知”参数。可以把 EasyParameters 想象成整数,而 ComplexParameters 是基于 EasyParameters 构造的大型矩阵

所以我使用上面的设置将SaveLoad 对象传入和传出文件,其中Create 使用构造函数,因为ComplexParam1ComplexParam2 存储在文件中,不需要计算再次。

问题

到目前为止,上面显示的方法对我来说效果很好。然而,当该方案也与类继承一起使用时,就会出现问题。因此,我正在寻找一种更好、更清洁的解决方案来解决我的问题。

在 C++ 中,我会重载构造函数并使两个可能的类创建可用,但这在 python 中不受支持。

感谢任何帮助、链接和建议。

【问题讨论】:

    标签: python oop file-io constructor


    【解决方案1】:

    我认为这是 @classmethod 装饰器的情况。例如,如果您将Load 方法更改为以下内容:

        @classmethod
        def Load(cls, Filename):
            # Do stuff
            return cls(ComplexA, ComplexB)
    

    然后你可以重写构造函数:

    class B(A):
        def __init__(self, complexA, complexB):
            # Whatever you want, including calling the parent constructor
    

    最后,您可以调用B.Load(some_file),它会调用B.__init__

    【讨论】:

      【解决方案2】:

      不需要重载,只需使用classmethod 替代构造方法即可。看看this questions 就是答案。

      class A (object):
      
          @classmethod
          def Load(cls, Filename):
              #read ComplexParam1 and ComplexParam2 and call constructor
              return cls(ComplexParam1, ComplexParam2)
      

      通过对类使用 cls 参数,它可以很好地用于继承。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-03
        • 2012-02-16
        • 2011-11-27
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多