top of page

__getitem__

  • Writer: VC Healy
    VC Healy
  • May 27, 2020
  • 1 min read

object.__getitem__(self,key)

class MyClass:
    def __getitem__(self, key):
	self.key = key
        print(self.key)
        return None

__getitem__(self, key)

Defines behaviour for when an item is accessed, using the notation self[key]. This is also part of both the mutable and immutable container protocols.

It should also raise appropriate exceptions:

TypeError if the type of the key is wrong

KeyError if there is no corresponding value for the key.


Called to implement evaluation of self[key].

For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method.

If key is of an inappropriate type, TypeError may be raised;

if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised.

For mapping types, if key is missing (not in the container), KeyError should be raised.


Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.


object.__reversed__(self)

Called (if present) by the reversed() built-in to implement reverse iteration.

It should return a new iterator object that iterates over all the objects in the container in reverse order.

If the __reversed__() method is not provided, the reversed() built-in will fall back to using the sequence protocol (__len__() and __getitem__()).

Objects that support the sequence protocol should only provide __reversed__() if they can provide an implementation that is more efficient than the one provided by reversed().

 
 
 

Kommentare


© 2020 by Vincent Healy. Proudly created with Wix.com

bottom of page