复合对象的python序列化
我有以下代码片段:复合对象的python序列化,python,serialization,pickle,composition,Python,Serialization,Pickle,Composition,我有以下代码片段: import pickle class Date: def __init__(self, d=1, m=1, y=1): self.Day = d self.Month = m self.Year = y def __str__(self): return str(self.Day) + "-" + str(self.Month) + "-" + str(self.Year) class Pe
import pickle
class Date:
def __init__(self, d=1, m=1, y=1):
self.Day = d
self.Month = m
self.Year = y
def __str__(self):
return str(self.Day) + "-" + str(self.Month) + "-" + str(self.Year)
class Person:
def __init__(self, n=0,dob=Date(0,0,0)):
self.no = n
self.DOB = dob
def __str__(self):
return "No = " + str(self.no) + ", DOB = " + str(self.DOB)
#main
f = open("a.dat", "wb")
d=dict()
p=Person()
p.no = int(raw_input("Enter empl no: "))
p.DOB.Day = int(raw_input("Enter day: "))
p.DOB.Month = int(raw_input("Enter Month: "))
p.DOB.Year = int(raw_input("Enter Year: "))
d[p.no] = p
p=Person()
p.no = int(raw_input("Enter empl no: "))
p.DOB.Day = int(raw_input("Enter day: "))
p.DOB.Month = int(raw_input("Enter Month: "))
p.DOB.Year = int(raw_input("Enter Year: "))
d[p.no] = p
pickle.dump(d,f)
f.close()
#now open the file again
f = open("a.dat", "rb")
d = pickle.load(f)
for p in d.values():
print str(p)
我有两个人存储在一个字典中,在序列化后保存在一个文件中。两个人都有不同的DOB,但从文件加载时,显示相同的DOB。
输入和输出如下:
Enter empl no: 1
Enter day: 1
Enter Month: 1
Enter Year: 2001
Enter empl no: 2
Enter day: 2
Enter Month: 2
Enter Year: 2002
No = 1, DOB = 2-2-2002
No = 2, DOB = 2-2-2002
这里怎么了?尽管两个对象的日期不同,但日期显示相同的原因。
请建议。
有一些关于的讨论,但如果我希望为不同的Person对象输入不同的日期,该怎么办?问题是在使用默认对象参数初始化时:
def __init__(self, n=0,dob=Date(0,0,0)):
正如您将在讨论中看到的,对方法的每次调用都不会调用Date
构造函数。相反,在第一次加载模块时调用一次,然后始终使用相同的实例。你认为你有不同的出生日期是错误的
编辑:在处理这种情况时,如果您仍然希望保留默认参数行为,通常的范例是分配None
,并检查其初始化。在您的情况下,这就是它的含义:
def __init__(self, n=0,dob=None):
# By calling `Date` in the initialiser's body, it's guaranteed to generate a new instance for every call
if dob is None:
dob = Date(0,0,0)
# At this point self.DOB is initialised with either a new instance or a given one
self.DOB = dob
这需要一个有效的答案,所以,我的Person类应该有:def uuu init uuu(self,n=0,dd=1,dm=1,dy=1):self.no=n self.DOB=Date(dd,dm,dy),这很有效!谢谢这是一个选择,但是如果你想保持你的设计,还有更好的选择。查看我的编辑。是的,这样更好:-)