[Tutor] classes and the deepcopy function

Michael python at mrfab.info
Sat Jan 5 03:45:21 CET 2008


I was trying to learn about classes in Python and have been playing 
around but I am having a problem with the deepcopy function. I want to 
have a function that returns a clean copy of an object that you can 
change without it changing the original, but no matter what I do the 
original changes as well. Can anyone give ma a pointer?

import copy

class point:
    "represents a point in 2d space"
    x = 0
    y = 0
    def printpoints(self):
        print "x is %g, y is %g" %(self.x, self.y)

class rectangle:
    "represents a rectangle"
    width = 0
    height = 0
    corner = point()

def move_rectangle(rect, dx, dy):
    rect2 = copy.deepcopy(rect)
    rect2.corner.x += dx
    rect2.corner.y += dy
    return rect2

r1 = rectangle()
r1.width = 20
r1.height = 40
r1.corner.x = 10
r1.corner.y = 10
r2 = move_rectangle(r1,5,2)
print 'Rectangle', r1.width, r1.height
print 'Rectangle 2', r2.width, r2.height

More information about the Tutor mailing list