[英]user defined class serialization and deserialization in python
I am very new to python : I want to serialize and deserialize my custom object in python.我对 python 很陌生:我想在 python 中序列化和反序列化我的自定义对象。 Please guide me on the same.
请指导我。 I have a sample class :
我有一个示例类:
import pickle
import json
class MyClass():
variable = "blah"
num = 10
def function(self):
print("this is a message inside the class.")
def get_variable():
return variable
def get_num():
return num
def main():
myObj = MyClass()
with open('/opt/infi/deeMyObj.txt', 'w') as output:
pickle.dump(myObj, output,pickle.HIGHEST_PROTOCOL)
with open('/opt/infi/deeMyObj.txt', 'r') as input:
myObjread = pickle.load(input)
print myObjread.get_variable()
print myObjread.get_num()
main()
I am getting following error :我收到以下错误:
Traceback (most recent call last):回溯(最近一次调用最后一次):
File "sample.py", line 30, in文件“sample.py”,第 30 行,在
main()
File "sample.py", line 27, in main文件“sample.py”,第 27 行,在主目录中
print myObjread.get_variable()
TypeError: get_variable() takes no arguments (1 given)类型错误:get_variable() 不接受任何参数(给定 1 个)
Main intention is to read the object back.主要目的是读回对象。
To expand on jasonharper's comment , your get_variable
and get_num
methods aren't referring to the class's member variables.为了扩展jasonharper 的评论,您的
get_variable
和get_num
方法不是指类的成员变量。 They should take the object as their first argument, eg他们应该将对象作为他们的第一个参数,例如
class MyClass:
...
def get_variable(self):
return self.variable
I think your serialization code is OK, but I might be wrong.我认为你的序列化代码没问题,但我可能错了。
(Aside) This is a bit off-topic, but another thing to note: when you define variables directly within the class
block, they're defined on the class, not on objects of that class. (旁白)这有点偏离主题,但要注意的另一件事是:当您直接在
class
块中定义变量时,它们是在类上定义的,而不是在该类的对象上定义的。 That happens to work out in this case, since Python will look for a class-level variable of the same name if it can't find one on the object.在这种情况下,这恰好可以解决,因为如果在对象上找不到同名变量,Python 将查找同名的类级变量。 However, if you store, say, a list in one of them and start modifying it, you'd end up sharing it between objects, which is probably not what you want.
但是,如果您在其中之一中存储一个列表并开始修改它,您最终会在对象之间共享它,这可能不是您想要的。 Instead you want to define them on in an
__init__
method:相反,您想在
__init__
方法中定义它们:
class MyClass:
def __init__(self):
self.variable = "blah"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.