0

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

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by foosion
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.