I need to use __getitem__
for all 7 arguments in my class but __getitem__
won’t let me so I tried to use a tuple
but I keep getting this error:
JavaScript
x
2
1
TypeError: cannot unpack non-iterable int object
2
What should I do?
JavaScript
1
4
1
def __getitem__(self, key):
2
name,author,category,Isbn_number,printing_house,date,number_of_order = key
3
return (self.name,self.author,self.category,self.Isbn_number,self.printing_house,self.date,self.number_of_order)
4
Advertisement
Answer
To make a getitem that returns the contents of each of the member variables given a key that is the same as the name of that member, you could have the class store the information in a dict and have your get_item return from that dict. E.g.:
JavaScript
1
7
1
class Book():
2
def __init__(self, name='Jud', author='Jill', category='YA'):
3
self.elements = {'name': name, 'author': author, 'category': category}
4
5
def __getitem__(self, key):
6
return self.elements[key]
7
Then with an instance of the class you should be able to do things like:
JavaScript
1
4
1
book = Book()
2
book['name']
3
book['author']
4