明星解包为自己的类 [英] star unpacking for own classes
问题描述
我想知道是否可以使用自己的类而不是像 list
和 tuple
。
class Agent(object):
def __init __(self,cards):
self.cards = cards
def __len __(self):
return len(self.cards)
def __iter __(self):
return self.cards
并且可以写
=代理([1,2,3,4])
myfunc(* agent)
TypeError:visualize()参数后面的*必须是一个序列,而不是代理
我必须实现哪些方法才能解压缩?
解决方案例外消息:
参数后面的*必须是序列
应该说,后的参数必须是可迭代的
。
由于这个原因,星号解包通常称为iterable unpacking。 请参阅 PEP 448(附加拆包概括)和 PEP 3132(扩展可迭代打开)。
编辑:看起来像是修复了python 3.5.2和3.6 < a>。将来它会说:
后面的参数必须是可迭代的
为了明星解包,你的类必须是可迭代的,即它必须定义一个 __ iter __ 返回一个迭代器:
class Agent(object):
def __init __ ):
self.cards = cards
def __len __(self):
return len(self.cards)
def __iter __(self):
return card in self.cards)
那么:
在[11]中:a = Agent([1,2,3,4])
在[12] :在python 2中,这将打印元组
1 2 3 4
I was wondering if it's possible to use star unpacking with own classes rather than just builtins like 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
And be able to write
agent = Agent([1,2,3,4])
myfunc(*agent)
But I get:
TypeError: visualize() argument after * must be a sequence, not Agent
Which methods do I have to implement in order to make unpacking possible?
解决方案 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
这篇关于明星解包为自己的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!