复合对象的python序列化

2024-10-02 00:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码段:

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

这里怎么了?尽管两个对象的日期不同,但日期显示相同的原因。 请建议。 有一些关于“Least Astonishment” in Python: The Mutable Default Argument的讨论,但是如果我希望为不同的Person对象输入不同的日期,该怎么办?你知道吗


Tags: noselfinputrawdefyearintperson
1条回答
网友
1楼 · 发布于 2024-10-02 00:22:45

问题是使用默认对象参数初始化时:

def __init__(self, n=0,dob=Date(0,0,0)):

正如您将在this讨论中看到的,并不是每次调用方法都调用Date构造函数。相反,当第一次加载模块时调用一次,然后总是使用同一个实例。你认为你有不同的出生日期是错误的。你知道吗

Edit:如果您仍然希望保持默认参数行为,那么在处理这样的情况时,常见的范例是赋值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

相关问题 更多 >

    热门问题