Deepcopy in Python

I have a class that looks like this at the beginning:

class PlacementNode:
    pos = Point3();
    
    def __init__(self, distance, x, y, z, xIn, yIn):
        self.pos.setX(x);
        self.pos.setY(y);
        self.pos.setZ(z);

I have a double loops that creates many PlacementNodes. When I’m finished with the loop, the PlacementNode.pos for every PlacementNode is exactly the same. Why do all instances of the class point to the same Point3() and is there a way to prevent this? I’m sure there is but I tried doing a deepcopy and that does not seem to work for me either.

Defining a variable outside the init scope makes it a static member – thus the same pointer for all class instances.
Use this instead:

class PlacementNode:
    def __init__(self, distance, x, y, z, xIn, yIn):
        self.pos = Point3()
        self.pos.setX(x)
        self.pos.setY(y)
        self.pos.setZ(z)

(or shorter:)

class PlacementNode:
    def __init__(self, distance, x, y, z, xIn, yIn):
        self.pos = Point3(x, y, z)

(or you could even inherit your class from Point3, if it’s that important.

Note that the semicolon at the end of a line is not needed in Python.

I actually assumed at one point that defining the Point3 out of the init method made it static so I changed all my code to something very similar to what you have. It caused other problems where the class had no idea that the Point3 was actually of type Point3. I will mess around with it a bit more.

I know the semicolon is not needed. I just come from a background of C/C++, C#, and Java so the code is more readable to me with semicolons :slight_smile:.