3

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)
1
  • 1
    Try setting centers as self.centers in __init__ method. Like this: def __init__(self): self.centres = np.zeros((3,2)). Same for id. Commented Jul 7 at 11:09

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! I should have read my book more carefully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.