简体   繁体   中英

Cannot unpack non-iterable int object

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:

TypeError: cannot unpack non-iterable int object

What should I do?

def __getitem__(self, key):
    name,author,category,Isbn_number,printing_house,date,number_of_order = key
    return (self.name,self.author,self.category,self.Isbn_number,self.printing_house,self.date,self.number_of_order)

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. Eg:

def __init__(self, name = 'Jud', author='Jill', category='YA'):
    self.elements = {'name':name,'author':author,'category':category}

def __getitem__(self, key):
    return self.elements[key]

Then with an instance of the class you should be able to do things like:

aBook['name']
aBook['author']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM