pythonnumpyclass

Using a class with numpy does not work correctly


I define an array of 4 corners

import numpy as np

class Corner():
    centres = np.zeros((3,2))
    id=0

corners=np.empty((4)).astype(Corner)

for i in range(4):
    corner=Corner()
    corner.id = i
    corners[i]=corner

The corners each contain an np.array called centres When I attempt to change just one entry for corners[1].centres ...

corners[1].centres[0]=[5,5]

... I find that all the other corners get updated as well.

Things work well if I just use numpy:

corners=np.zeros((4,3,2))

def show(corners):
    for i in range(4):
        print("[",end="")
        for j in range(3): 
            print(corners[i][j],end="")
        print("] ")
    print()
 
show(corners)
print("set corners[1][0]=[5,5]...")
corners[1][0]=[5,5]
show(corners)

Solution

  • You would have to use instance variables. Define centres in the __init__ method so each Corner instance will have its own centres array:

    import numpy as np
    
    class Corner:
        def __init__(self):
            self.centres = np.zeros((3, 2))
            self.id = 0
    
    corners = np.empty((4,), dtype=object)  # Note the comma for shape and dtype=object
    
    for i in range(4):
        corner = Corner()
        corner.id = i
        corners[i] = corner
    

    Now changing one doesn't affect the others:
    corners[1].centres[0] = [5, 5]Also note the use of dtype=object when making arrays of custom Python objects in corners = np.empty((4,), dtype=object)