Can property getters and setters have additional arguments? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Can property getters and setters have additional arguments? (/thread-30635.html) |
Can property getters and setters have additional arguments? - pjfarley3 - Oct-29-2020 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: 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: Please tell me what I am doing wrong here.Peter RE: Can property getters and setters have additional arguments? - Askic - Oct-29-2020 Not sure what are you trying to achieve, but please execute the following code: 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('This is what is created inside Matrix object: ') print(type(mygal.visited)) print(mygal.visited) print('This is how mycoord looks like: ') print(type(mycoord)) print(mycoord)Attribute visited is very strange to me. RE: Can property getters and setters have additional arguments? - pjfarley3 - Oct-30-2020 I added your code and reduced the Matrix size from 10 to to 3 so output would be shorter. Below is the output. The arrays in the class and the Coord() value are NUMPY arrays, not regular python arrays. My question is still whether I am off-base in thinking that property methods and getter/setters can take additional positional parameters as in my example. Peter
|