为自己的班级开明星

发布于 2021-01-29 16:34:58

我想知道是否可以对自己的类使用star拆包,而不仅仅是像listand这样的内建函数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

为了使拆包成为可能,我必须实现哪些方法?

关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    异常消息:

    *之后的参数必须是序列

    应该真的说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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看