[Tutor] is this use or abuse of __getitem__ ?
eryksun
eryksun at gmail.com
Fri Sep 14 14:50:55 CEST 2012
On Fri, Sep 14, 2012 at 8:16 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> Am I abusing the __getitem__ method, or is this just a creative way of using it?
No, you're using it the normal way. The item to get can be an index, a
key, or even a slice.
http://docs.python.org/reference/datamodel.html#object.__getitem__
> if not isinstance(key, (int, float)):
> raise TypeError
Instead you could raise a TypeError if "not hasattr(key, '__int__')"
since later you call int(key).
> if abs(key) > self.nCases:
> raise IndexError
You might also want to support slicing. Here's an example:
http://stackoverflow.com/a/2936876/205580
More information about the Tutor
mailing list