python加载实例快

时间:2017-11-11 20:03:02

标签: python python-2.7 pycharm

我有一个包含我要保存和加载的数据的类。 我还希望我的环境(PyCharm)将对象y = MyClass.load(' C:\ some path.pkl')识别为MyClass实例,并在将来的行中自动完成。

我在课堂上有两个功能,'加载'识别y,而快速加载'没有按'吨。但如果加载的实例包含大量数据,则后者要快得多(最多10次)。 有没有办法控制加载的对象实例而不将整个数据复制到新的类实例?

这是我的代码的相关部分:

import cPickle as pickle
from copy import deepcopy

def save(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, -1)


def load(filename):
    with open(filename, 'rb') as input_:
        return pickle.load(input_)

class MyClass:
    def __init__(self, save_path,run_time=0):
        ...

    def save(self, path=None):
        save(self, path)

    @staticmethod
    def load(path):
        ad_obj = MyClass('', 0)
        ad_obj.__dict__ = deepcopy(load(path).__dict__)
        return ad_obj

    @staticmethod
    def fast_load(path):
        return load(path)

感谢

1 个答案:

答案 0 :(得分:0)

使用Python 3,这很容易。您只需向load函数添加一个返回类型注释(注意您必须在load之后定义MyClass):

def load(filename): -> MyClass
    ...

使用Python 2,你必须通过在文档字符串中添加args来做更复杂的事情,如the PyCharm docs中所述。

就个人而言,我喜欢Google style docstrings

def load(filename):
    """Load something.

    Returns:
        MyClass

    """