__getitem__(x, i) . The method __getitem__(self, key) defines behavior for when an item is accessed, using the notation self[key] . This is also part of both the mutable and immutable container protocols. Unlike some other languages, Python basically lets you pass any object into the indexer.
The __iter__() method returns the iterator object itself. If required, some initialization can be performed. The __next__() method must return the next item in the sequence. On reaching the end, and in subsequent calls, it must raise StopIteration .
__getitem__ and __setitem__ in Python They are predefined methods that simplify many operations that can be performed on a class instance, like __init__(), __str__(), __call__() etc. These methods are very helpful because they are used in binary operations, assignment operations, unary and binary comparison operations.
According to python documentation object. __dict__ is A dictionary or other mapping object used to store an object's (writable) attributes. Or speaking in simple words every object in python has an attribute which is denoted by __dict__. And this object contains all attributes defined for the object.
I have an object with a dictionary that I want to access via __getitem__
as well as iterate over (values only, keys don't matter) but am not sure how to do it.
For example:
Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10)
>>> class Library(object):
... def __init__(self):
... self.books = { 'title' : object, 'title2' : object, 'title3' : object, }
... def __getitem__(self, i):
... return self.books[i]
...
>>> library = Library()
>>> library['title']
<type 'object'>
>>> for book in library:
... print book
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __getitem__
KeyError: 0
>>>
How do I tell it to simply return the object
for each item in the dictionary (the key doesn't matter) ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With