Creating Classes Dynamically?

John Mitchell johnm at
Thu Apr 20 19:12:45 CEST 2000

On Thu, 20 Apr 2000, Jerome Chan wrote:

> Is there a way to create an object of a class from a string?

You can save and restore objects using the 'pickle' module:

import pickle

class Struct:

# create new object 'j'
j = Struct() = 'john'
j.title = 'stud'

# package it up
x = pickle.dumps(j)
print x

# "x" is a semi-printable representation of object "j":
# => looks something like "(i__main__  Struct  p0  
# (dp1  S'title'  p2  S'stud'  p3  sS'name'  p4  S'john'  p5  sb."
z = pickle.loads(x)

# "z" is a new object, loaded from "x", which is a
# copy of our original object.  To test it, print out its name.

# => "john"

Also check out the shelve and binascii modules.

- j

More information about the Python-list mailing list