How to copy class objects?

RajGopal Srinivasan raj at grserv.med.jhmi.edu
Mon Feb 12 08:38:44 EST 2001


If I understand your question correctly (which I probably don't ) the
following example
is one possible solution. Of course there is no copying at all here,
just
dynamic class definition.

raj

#### stack.py
from types import *
codeTemplate = """class %s:
    __doc__ = "%s"
    elementType = %s
    def __init__(self):
        self.data = []
    def push(self, elem):
        assert type(elem) == self.elementType
        self.data.append(elem)
    def pop(self):
        return self.data.pop()\n
"""

def StackFactory(className, classDoc, elType):
    # if we are paranoid we should use rexec
    exec(codeTemplate%(className, classDoc, elType), globals())


### stacktest.py
import stack
stack.StackFactory('IntStack', 'Stack of Ints', 'IntType')
stack.StackFactory('FloatStack', 'Stack of Floats', 'FloatType')

print stack.IntStack.__doc__
print stack.FloatStack.__doc__

ints = stack.IntStack()

for i in range(10):
    ints.push(i)

while 1:
    try:
        print ints.pop()
    except IndexError:
        break
try:
    ints.push(1.0)
except AssertionError:
    print 'Failed to push float into IntStack'
###



More information about the Python-list mailing list