Har Har -5 years ago 118
Python Question

Implement packing/unpacking in an object

I have a class that only contains attributes and I would like packing/unpacking to work on it. What

should I implement to get this behaviour?

class Item(object):

def __init__(self, name, age, gender)
self.name = name
self.age = age
self.gender = gender

a, b, c = Item("Henry", 90, "male")

I would like to avoid using a

Answer Source

You can unpack any Iterable. This means you need to implement the __iter__ method, and return an iterator. In your case, this could simply be:

def __iter__(self):
    return iter((self.name, self.age, self.gender))

Alternatively you could make your class an Iterator, then __iter__ would return self and you'd need to implement __next__; this is more work, and probably not worth the effort.

For more information see What exactly are Python's iterator, iterable, and iteration protocols?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download