It’s not a real world program but I would like to know why it can’t be done.
I was thinking about numpy.r_ object and tried to do something similar but just making a class and not instantiating it.
a simple code (has some flaws) for integers could be:
class r_:
@classmethod
def __getitem__(clc, sl):
try:
return range(sl)
except TypeError:
sl = sl.start, sl.stop, sl.step
return range(*(i for i in sl if i is not None))
but as I try to do r_[1:10] i receive TypeError: 'type' object is not subscriptable.
Of course the code works with r_.__getitem__(slice(1,10)) but that’s not what I want.
Is there something I can do in this case instead of using r_()[1:10]?
The protocol for resolving
obj[index]is to look for a__getitem__method in the type ofobj, not to directly look up a method onobj(which would normally fall back to looking up a method on the type ifobjdidn’t have an instance attribute with the name__getitem__).This can be easily verified.
I don’t know why exactly it works this way, but I would guess that at least part of the reason is exactly to prevent what you’re trying to do; it would be surprising if every class that defined
__getitem__so that its instances were indexable accidentally gained the ability to be indexed itself. In the overwhelming majority of cases, code that tries to index a class will be a bug, so if the__getitem__method happened to be able to return something, it would be bad if that didn’t get caught.Why don’t you just call the class something else, and bind an instance of it to the name
r_? Then you’d be able to dor_[1:10].