Custom double star operator for a class?

后端 未结 2 1696
孤独总比滥情好
孤独总比滥情好 2021-02-13 14:03

How does one implement custom double star operator (**) for unpacking, similar to how __iter__ works with single star operator (*)?

<
2条回答
  •  广开言路
    2021-02-13 14:44

    As @ShadowRanger says, implement Mapping. Here's an example:

    from collections.abc import Mapping
    
    class Foo(Mapping):
        def __iter__(self):
            yield "a"
            yield "b"
    
        def __len__(self):
            return 2
    
        def __getitem__(self, item):
            return ord(item)
    
    f = Foo()
    
    print(*f)
    print(dict(**f))
    

    The program outputs:

    a b
    {'a': 97, 'b': 98}
    

提交回复
热议问题