在dict中的python 33 pickle类实例

时间:2013-03-28 21:02:44

标签: python python-3.x pickle cpython

以下代码

import pickle
class Member:
    global members
    try:
        with open('member dict.txt','rb') as f:
            members=pickle.load(f)
    except:
        members={}

    def __init__(self,name,info,new=True):
        if name in members and new:
            print('name is taken')
            self.name='Void'
            self.info={'Void':'Void'}
        else:
            self.info=info
            self.name=name
            members[name]=self
            if new:
                with open('member dict.txt','wb') as f:
                    pickle.dump(members,f)
    def __getstate__(self):
        return[self.name,self.info]
    def __setstate__(self,d):
        return Member(d[0],d[1],False)

然后处于空闲状态(在第一个代码中prssing f5之后)我输入

PJ=member('P',{})

我关闭空闲然后重新打开它并输入

members

返回{}

1 个答案:

答案 0 :(得分:1)

我自己运行代码,运行程序的第二时间,错误为AttributeError: 'module' object has no attribute 'Member'。在你的课程被正确构建之前,你正试图给你的课程搞砸。要扩展第一条评论,将members放入类定义使您的代码失败的原因。将它移到类定义下面,它将起作用。

class Member:
    def __init__(self, name, info, new=True):
        ...
    ...

try:
    with open('member dict.txt', 'rb') as f:
        members = pickle.load(f)
except Exception as e:
    members = {}