python - __getitem__ and __setitem__ not being called -
i have following class definition:
class codes(): def __new__(self, inp): self.data = np.zeros((50,50)) self.capacity = 50 self.size = 6 self.data[:self.size,:self.size] = inp self.x = 0 self.y = 0 return self def __setitem__(self,coords,value): x = coords[0] y = coords[1] if max(x,y) >= self.capacity: self.capacity *= 2 newdata = np.zeroes((self.capacity,)) newdata[:self.size,:self.size] = self.data self.data = newdata self.data.__setitem__(coords,value) if max(x,y) >= self.size: print("expanding") self.size = max(x,y) print ("debug") def __getitem__(self,coords): x = coords[0] y = coords[1] return self.data[x,y]
the , set methods don't seem being called. i'm initialising with:
inp = np.array([[20151125,18749137,1728984,30943339,10071777,33511524], [31916031,21629792,16929656,7726640,15514188,4041754], [16080970,8057251,1601130,7981243,11661866,16474243], [24592653,32451966,21345942,9380097,10600672,31527494], [77061,17552253,28094349,6899651,9250759,31663883], [33071741,6796745,25397450,24659492,1534922,27995004]]) = codes(inp)
if try execute print(a[1,1])
, error:
traceback (most recent call last): file "c:/users/cotont/dropbox/advent of code/advent of code 25-1.py", line 55, in <module> print(a[1,1]) typeerror: 'type' object not subscriptable
if try execute a[49,49] = 1
, get:
traceback (most recent call last): file "c:/users/cotont/dropbox/advent of code/advent of code 25-1.py", line 55, in <module> a[49,49] = 1 typeerror: 'type' object not support item assignment
why custom methods not being called, , how fix it?
you misunderstanding __new__
or accidentally used should have used __init__
. returning codes
object itself returning self
:
def __new__(self, inp): # ... return self
__new__
called static method on class , expected produce new instance in method.
because returned type object (the class), __getitem__
, __setitem__
looked on type
(the default metaclass) (see special method lookup), fails.
you wanted use __init__
there instead; __init__
called on already-created instance:
class codes(): def __init__(self, inp): self.data = np.zeros((50,50)) self.capacity = 50 self.size = 6 self.data[:self.size,:self.size] = inp self.x = 0 self.y = 0
__init__
doesn't need return (and returns ignored anyway), can drop return self
line altogether.
if feel must use __new__
(perhaps because subclassing immutable type), @ least create instance super().__new__()
:
class codes(): def __new__(cls, inp): instance = super(codes, cls).__new__(cls) instance.data = np.zeros((50,50)) instance.capacity = 50 instance.size = 6 instance.data[:self.instance,:instance.size] = inp instance.x = 0 instance.y = 0 return instance
but using __init__
instead simpler.
Comments
Post a Comment