star unpacking for own classes

寵の児 提交于 2019-12-01 05:13:44

The exception message:

argument after * must be a sequence

should really say, argument after * must be an iterable.

Often star-unpacking is called "iterable unpacking" for this reason. See PEP 448 (Additional Unpacking Generalizations) and PEP 3132 (Extended Iterable Unpacking).

Edit: Looks like this has been fixed for python 3.5.2 and 3.6. In future it will say:

argument after * must be an iterable


In order to have star unpack, your class must be an iterable i.e. it must define an __iter__ that returns an iterator:

class Agent(object):
    def __init__(self, cards):
        self.cards = cards
    def __len__(self):
        return len(self.cards)
    def __iter__(self):
        return (card for card in self.cards)

then:

In [11]: a = Agent([1, 2, 3, 4])

In [12]: print(*a)  # Note: in python 2 this will print the tuple
1 2 3 4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!