Oct-29-2020, 06:31 AM
I am trying to implement getters and setters in a class using a numpy array as the base instance value, but I am not able to pass an array index argument to the getter function (and probably not to the setter function, but it never gets that far).
The code is as follows:
Peter
The code is as follows:
import numpy as np class Matrix: def __init__(self, msize): self.msize = msize self.mvalues = np.full([msize + 2, msize + 2, msize + 2], -1, dtype=np.int32) self.mvalues[1:-1, 1:-1, 1:-1] = 0 self.visited = np.zeros([msize + 2, msize + 2, msize + 2], dtype=np.int32) @property def visits(self, coord): return self.visited[coord[0], coord[1], coord[2]] @visits.setter def incr_visits(self, coord, incr): self.visited[coord[0], coord[1], coord[2]] += incr def Coord(x, y, z): return np.full([3,], (x, y, z), dtype=np.int32) mycoord = Coord(1, 2, 3) print("mycoord={}".format(mycoord)) mygal = Matrix(10) print("Before set:{}".format(mygal.visits(mycoord))) mygal.incr_visits(mycoord, 10) print("After set:{}".format(mygal.visits(mycoord)))And this is the output I get:
Output:mycoord=[1 2 3]
Traceback (most recent call last):
File "C:\Users\MyUser\Test\clstest4.py", line 28, in <module>
print("Before set:{}".format(mygal.visits(mycoord)))
TypeError: visits() missing 1 required positional argument: 'coord'
Please tell me what I am doing wrong here.Peter