Python Save A Class

Let me share a little code snippet I use at times which I call “python save a class”. I came up with a very simple and easy way to do that. Check out my code snippet below.



import cPickle
import traceback

class someClass():
    def __init__(self):
        #set name from variable name.
        def_name = text[:text.find('=')].strip() = def_name

            #to demonstrate
            self.someAttribute = 'bla'
            self.someAttribute2 = ['more']


    def save(self):
        """save class as"""
        file = open('.txt','w')

    def load(self):
        """try load"""
        file = open('.txt','r')
        dataPickle =

        self.__dict__ = cPickle.loads(dataPickle)

    def __str__(self):
        return str(self.__dict__)

The class is saved as whatever the name of the class instance is. Please not that this works with all datatypes that Pickle supports.


myClass = someClass()

Will try to load a saved class called “myClass.txt” otherwise set some sample values and save the class. Feel free to use this code.


I would also like to give credit to StackOverflow – Getting an instance name inside class init which showed the cool little trick of how to getting the class instance name.

I hope I was able to show you how to save a class in python. Let me know if you have any questions or comments.

The perfect season to determination soundness problem is before any visible sign appears. Actually there isn’t anything you can’t purchase on the Internet anymore. Whereas erectile disfunction is more common among older men, that doesn’t something you just have to live with. What about “canadian pharmacy cialis 5 mg” and “cialis canadian pharmacy“? In our generation, there are divers options for those ones who suffer from erectile disfunction. You may have heard about “canadian pharmacy online cialis“. More information about the question available at “canadian pharmacy cialis 20mg“. Why it happen? Can sexual disorders in men be prevented? If you get any prescription remedies like Viagra, check with a dispenser that they are sure to take with your other remedies.