Hey all,

Here's my problem: I have a class that I want to be able to save and and load. But I need the class to be mutable I guess. Check it out:

class Tool:
    def __init__(self,name,function):
        self.name = name
        self.function = function
        self.savename = self.name + '.txt'


    def save(self):
        file = open(self.savename,'wb')
        pickle.dump(self,file)
        file.close()

    def load(self):
        print self.savename
        file = open(self.savename,'rb')
        self = pickle.load(file)
        file.close()

    def __str__(self):
        myT = (self.name,self.function)
        s = "Name: %s, Function: %s" %myT
        return s


x = Tool("hammer","pounding nails")
x.save()

print x

y = Tool("wrench","tightening")

y.savename = 'hammer.txt'

y.load()

print y

I'd like y to be equal to x after this executes, but print y returns: Name: wrench, Function: tightening

if you change the pickle statements to

pickle.dump((self.name, self.function),file)
and
(self.name,self.function) = pickle.load(file)

Then it works. You can save all of the class elements to some structure if you want and pickle that structure.

HTH

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.