明星为自己开箱 类

star unpacking for own classes

我想知道是否可以使用自己的 类 进行星号解包,而不是像 listtuple.

这样的内置函数
class Agent(object):
    def __init__(self, cards):
        self.cards = cards
    def __len__(self):
        return len(self.cards)
    def __iter__(self):
        return self.cards

并且会写

agent = Agent([1,2,3,4])
myfunc(*agent)

但我得到:

TypeError: visualize() argument after * must be a sequence, not Agent

我必须执行哪些方法才能进行解包?

异常信息:

argument after * must be a sequence

真的应该说,argument after * must be an iterable.

通常星形拆包被称为 "iterable unpacking" 就是因为这个原因。 参见 PEP 448 (Additional Unpacking Generalizations) and PEP 3132 (Extended Iterable Unpacking)

编辑:看起来已经 fixed for python 3.5.2 and 3.6。将来它会说:

argument after * must be an iterable


为了让 star 解包,你的 class 必须是一个可迭代的,即它必须定义一个 __iter__ 那个 returns 一个迭代器:

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)

然后:

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