[Python] Using a class with numpy does not work correctly

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    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=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[j],end="")
    print("] ")
    print()

    show(corners)
    print("set corners[1][0]=[5,5]...")
    corners[1][0]=[5,5]
    show(corners)

    Continue reading...

Compartilhe esta Página