0

以下代码

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)

然后在空闲(在第一个代码中按 f5 之后)我输入

PJ=member('P',{})

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

members

它返回{}

4

1 回答 1

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 = {}
于 2013-04-08T17:38:26.740 回答