简体   繁体   English

存储包含功能的数据

[英]Storing data that includes functions

What I have is a list types of data, each identified by a name. 我所拥有的是列表类型的数据,每个数据都由一个名称标识。 For example 'length' and 'weight'. 例如'长度'和'重量'。 These are used to read and write bytes from files. 这些用于从文件读取和写入字节。 Each metric stores a different amount of bytes, so I have a class Metric that stores for example a description and a byte length for the metric. 每个度量标准存储不同的字节数,因此我有一个类度量标准,用于存储度量标准的描述和字节长度。 Then, I can just keep a JSON file or an XML file of metric definitions that can be added to whenever. 然后,我可以保留一个JSON文件或一个可以随时添加的度量标准定义的XML文件。

I now want to differentiate how these bytes are read and written by adding a to_bytes and from_bytes method to the class. 我现在想要通过向类添加to_bytes和from_bytes方法来区分这些字节的读写方式。 I could store the function definition as a string in the JSON file and just eval() it, or I could write separate child classes for each metric. 我可以将函数定义存储为JSON文件中的字符串,只需将其存储为eval(),或者我可以为每个指标编写单独的子类。

What is the best way to store function definitions alongside other data? 将函数定义与其他数据一起存储的最佳方法是什么? I'm open to any suggestions, but the best solution is one that keeps it easy to manually add new metrics to the collection. 我对任何建议持开放态度,但最好的解决方案是让人们可以轻松地手动将新指标添加到集合中。

you can pickle a function like everything else: 你可以像其他一样腌制一个功能:

import pickle

def foo(x):
    return x*x

with open('myfile', 'wb') as f:
    pickle.dump(foo, f)

with open('myfile', 'rb') as f:
    moo = pickle.load(f)

print(moo(3)) 打印(MOO(3))

output: 输出:

9

also works for the whole class: 也适用于全班:

import pickle

class MyClass:
    def foo(x):
        return x*x

with open('myfile', 'wb') as f:
    pickle.dump(MyClass, f)

with open('myfile', 'rb') as f:
    LoadedClass = pickle.load(f)

print(LoadedClass.foo(3))

output: 输出:

9

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

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