Implement packing/unpacking in an object

前端 未结 2 946
甜味超标
甜味超标 2020-12-03 15:39

I have a class that only contains attributes and I would like packing/unpacking to work on it. What collections.abc should I implement to get this behaviour?

2条回答
  •  心在旅途
    2020-12-03 16:34

    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?


    Per the question I linked above, you could also implement an iterable with __getitem__:

    def __getitem__(self, index):
        return (self.name, self.age, self.gender)[index]
    

提交回复
热议问题