Reputation: 11
the following code
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)
then in idle (after prssing f5 in the first code) I type
PJ=member('P',{})
I close idle then reopen it and type
members
it returns {}
Upvotes: 0
Views: 183
Reputation: 9901
I ran your code myself, and the second time your program is run, the error is AttributeError: 'module' object has no attribute 'Member'
. You're trying to unpickle your class before it's properly been constructed. To extend on the first comment, putting members
into the class definition is what's making your code fail. Move it below the class definition, and it will work.
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 = {}
Upvotes: 1