为自己的班级开明星
问题内容:
我想知道是否可以对自己的类使用star拆包,而不仅仅是像list
and这样的内建函数tuple
。
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 an iterable
。
由于这个原因,通常将星形拆包称为 “可重复拆包” 。 请参阅 PEP
448(其他拆包概述)
和PEP
3132(扩展的可迭代拆包)
。
编辑:看起来这已 为python 3.5.2和3.6修复。将来会说:
*之后的参数必须是可迭代的
为了解开星标,您的类必须是可迭代的,即它必须定义一个__iter__
返回迭代器的:
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